为什么 List<String>.toArray() 返回 Object[] 而不是 String[]?如何解决这个问题? [英] why does List&lt;String&gt;.toArray() return Object[] and not String[]? how to work around this?

查看:28
本文介绍了为什么 List<String>.toArray() 返回 Object[] 而不是 String[]?如何解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道为什么 Java 1.6 有这种行为:

Does anybody know why Java 1.6 has this behaviour:

List<String> list = ArrayList<String>();
String[] arr = (String[]) list.toArray();

我得到一个 ClassCastException,因为它返回 Object[] 而不是 String[].

And I get a ClassCastException, because it returns Object[] and not String[].

我以为List.toArray() 应该返回 T[] - 不是吗?有没有人知道为什么语言中存在这种不便?以及如何解决这个问题?如何从 List 获取 String[] 而不遍历项目?

I thought List<T>.toArray() should return T[] - no? Does anyone have an answer why this inconvenience exists in the language? And also how to work around this? How do I get a String[] from List<String> without looping thru the items?

推荐答案

您需要传入一个数组,以便toArray 可以将其运行时类型用作提示.尝试 toArray(new String[0]) 代替.你也可以传入一个预先确定大小的数组.

You need to pass in an array so its runtime type can be used as a hint by toArray. Try toArray(new String[0]) instead. You can also pass in a pre-sized array.

要理解,请考虑要进行何种类型的擦除

To understand, consider what type erasure would have to do to make

new T[4]

工作.如果 Java 允许这样做,那么它在擦除后能做的最好的事情是

work. If Java allowed that, the best it could do post erasure is

new Object[4]

大多数 toArray 实现使用 java.lang.reflect.Array 构造正确类型的输出数组给定作为 Class<传递的类型提示/代码>.

Most toArray implementations use java.lang.reflect.Array to construct an output array of the right type given a type hint passed as a Class.

这篇关于为什么 List<String>.toArray() 返回 Object[] 而不是 String[]?如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆