Domanda

I need this code, but i get this error:

Ljava.lang.Object; cannot be cast to java.lang.String

public Object[] getAllKeys (){

    return keys.toArray(new Object[keys.size()]); 
}

public String[] getNames (){

    return ((String[])super.getAllKeys()); <- Error here. Can't cast, why?
}
È stato utile?

Soluzione 2

toArray() returns an array of Objects. If you want to create an array of Strings out of it, you will have to do it yourself. For example,

Object [] objects = super.getAllKeys();
int size = objects.size();
String [] strings = new String[size];

for (int i = 0; i < size; i++)
  strings[i] = objects[i].toString();

or something similar... Hope this is useful.

Altri suggerimenti

The type of the array is Object[] so it cannot know that it contains only Strings. It is quite possible to add a non-String object to that array. As a result the cast is not allowed.

You can return Object[] and then cast each of the objects within that array to string. i.e. (String)arr[0] or you can create a new String[] array and copy all the elements over before returning it.

Every String is an Object. Every Object is NOT a String.

You cannot do the cast, because even though Object is a base class of String, their array classes Object[] and String[] classes are unrelated.

You can fix this problem by introducing an additional method that allows taking a typed array:

public Object[] getAllKeys (){
    return getAllKeys(new Object[keys.size()]); 
}
// Depending on your design, you may want to make this method protected
public <T> T[] getAllKeys(T[] array){
    return keys.toArray(array); 
}
...
public String[] getNames (){
    return super.getAllKeys(new String[keys.size()]);
}

This code takes advantage of the other overload of toArray, which accepts a typed array as an argument.

This cannot be done implicitly since the runtime cannot know that the elements in Object[] are all String types.

If you don't want to code a loop yourself, then one way to coerce is to use

String[] myStringArray = Arrays.asList(keys).toArray(new String[keys.length]);

I think that this will happen without any string copies being taken: asList() binds to the existing array data and toArray uses generics which are removed at runtime anyway due to type erasure. So this will be faster than using toString() etc. Don't forget to deal with any exceptions though.

Try the following snippet

Object[] obj = {"Red","Green","Yellow"}; String[] strArray = (String[]) obj; // Casting from Object[] to String[]

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top