为什么Java的Collection< E> .ArArray()返回一个Object []而不是一个E []? [英] Why does Java's Collection<E>.toArray() return an Object[] rather than an E[]?

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

问题描述

在Java泛型之前, Collection.toArray()无法知道开发者期望的数组类型(特别是对于空集合)。根据我的理解,这是成语 collection.toArray(new E [0])背后的主要理由。

Before Java generics, Collection.toArray() had no way to know which type of array the developer expected (particularly for an empty collection). As I understand it, this was the main rationale behind the idiom collection.toArray(new E[0]).

使用泛型, Collection< E> .toArray()只能返回一个包含 E /或其专业化。我不知道为什么返回类型仍然是 Object [] 而不是 E [] 。在我看来,返回 E [] 而不是 Object [] 不应该破坏现有代码。

With generics, Collection<E>.toArray() can only return an array full of instances of E and/or its specialisations. I wonder why the return type still is as Object[] rather than E[]. In my opinion, returning an E[] instead of Object[] should not break existing code.

请参阅: Collection.toArray() Collection.toArray(T []) 和相关主题 java:(String [])List.toArray()提供ClassCastException

推荐答案

这是一个很好的问题。答案是,泛型也被称为擦除。它不只是一个名字。由泛型编码的信息仅在编译时使用,然后被删除。因此,JVM甚至不知道这个泛型类型 E ,因此它不能创建数组 E []

It is a very good question. The answer is that generics are also called "erasures." It is not just a name. The information coded by generics is used at compile time only and then is removed. So, JVM even does not know this generic type E, so it cannot create array E[].

其他方法 toArray(T [] a)在运行时从参数接收有关类型的信息。这是该方法的原型是< T> T [] toArray(T [] a):它获取类型T的数组,并且可以返回类型T的数组。类型作为参数传递。

Other method toArray(T[] a) receives the information about the type from the argument at runtime. This is the reason this method's prototype is <T> T[] toArray(T[] a): it gets array of type T and can return array of type T. The type is passed as a parameter.

这篇关于为什么Java的Collection&lt; E&gt; .ArArray()返回一个Object []而不是一个E []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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