java: (String[])List.toArray() gives ClassCastException

感情迁移 提交于 2019-11-26 11:14:52

This is because when you use

 toArray() 

it returns an Object[], which can't be cast to a String[] (even tho the contents are Strings) This is because the toArray method only gets a

List 

and not

List<String>

as generics are a source code only thing, and not available at runtime and so it can't determine what type of array to create.

use

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

which allocates the right kind of array (String[] and of the right size)

You are using the wrong toArray()

Remember that Java's generics are mostly syntactic sugar. An ArrayList doesn't actually know that all its elements are Strings.

To fix your problem, call toArray(T[]). In your case,

String[] v3 = v2.toArray(new String[v2.size()]);

Note that the genericized form toArray(T[]) returns T[], so the result does not need to be explicitly cast.

MakNe

String[] str = new String[list.size()];

str = (String[]) list.toArray(str);

Use like this.

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