Casting Object array into String array throws ClassCastException [duplicate]

徘徊边缘 提交于 2021-01-27 05:30:34

问题


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 Objects. You need to call the overload which takes the output array as the parameter, and pass an array of Strings, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!