Question

public String[] getAllKeys (){

    Object[] keysCopy = new Object[keys.size()];
    keysCopy = keys.toArray();

    return ((String[])keysCopy());
}

Why this gives me Ljava.lang.Object; cannot be cast to [Ljava.lang.String??

Was it helpful?

Solution

It is because you have object array and Object[] cannot be cast to String[]. The reverse is possible. Its because Object IS NOT A String and String IS A Object.

If you are sure that the content of keys is collection of String, then you can use keys.toArray(new String[keys.size()]);

public String[] getAllKeys(){
    return keys.toArray(new String[keys.size()]);
}

OTHER TIPS

`return Arrays.copyOf(keysCopy, keysCopy.length, String[].class);`

An Object[] is not a String[].

Try this, it works.

public String[] getAllKeys (){
Object[] keysCopy = new Object[keys.size()];
keysCopy = keys.toArray(new String[0]);
return (String[]) keysCopy;
}

For more you can read this [post] (How to convert object array to string array in Java)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top