javaarraysobjectjava.lang.class

Can't return a Object[] casted as String[]


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


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()]);
    }