java 将 Object 数组转换为 String 数组会抛出 ClassCastException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17915247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:35:53  来源:igfitidea点击:

Casting Object array into String array throws ClassCastException

javaarraysstringobjectclasscastexception

提问by Script_Junkie

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.

我不明白为什么?任何解决方案,解释表示赞赏。

回答by dasblinkenlight

This is because the parameterless toArrayproduces 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:

这是因为无参数toArray产生了一个Objects数组。您需要调用将输出数组作为参数的重载,并传递一个Strings数组,如下所示:

String[] names = (String[]) list.toArray(new String[list.size()]);

In Java 5 or newer you can drop the cast.

在 Java 5 或更新版本中,您可以删除强制转换。

String[] names = list.toArray(new String[list.size()]);

回答by dasblinkenlight

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.

您正在尝试从Object[]. 类本身是一个类型为 的数组Object。您必须逐个进行转换,将元素添加到新数组中。

Or you could use the method already implemented for that, by doing this:

或者你可以使用已经实现的方法,这样做:

list.toArray(new String[list.size()]);