问题
List<String> list = getNames();//this returns a list of names(String).
String[] names = (String[]) list.toArray(); // throws class cast exception.
I don't understand why ? Any solution, explanation is appreciated.
回答1:
This is because the parameterless toArray
produces an array of Object
s. You need to call the overload which takes the output array as the parameter, and pass an array of String
s, like this:
String[] names = (String[]) list.toArray(new String[list.size()]);
In Java 5 or newer you can drop the cast.
String[] names = list.toArray(new String[list.size()]);
回答2:
You are attempting to cast from a class of Object[]
. The class itself is an array of type Object
. You would have to cast individually, one-by-one, adding the elements to a new array.
Or you could use the method already implemented for that, by doing this:
list.toArray(new String[list.size()]);
来源:https://stackoverflow.com/questions/17915247/casting-object-array-into-string-array-throws-classcastexception