1
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??

user2911701
  • 69
  • 1
  • 9
  • 1
    Use the overloaded method `toArray(T[] arr)` – Alexis C. Apr 24 '14 at 09:24
  • possible duplicate of [java: (String\[\])List.toArray() gives ClassCastException](http://stackoverflow.com/questions/5690351/java-stringlist-toarray-gives-classcastexception) – Alexis C. Apr 24 '14 at 09:25

4 Answers4

2

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()]);
}
sanbhat
  • 17,162
  • 6
  • 47
  • 63
0
`return Arrays.copyOf(keysCopy, keysCopy.length, String[].class);`
sadhu
  • 1,371
  • 7
  • 14
0

An Object[] is not a String[].

Bohemian
  • 389,931
  • 88
  • 552
  • 692
0

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)

Community
  • 1
  • 1
Ankit
  • 17
  • 5