Java:在集合的遍历中,关于 Object[] toArray() 方法的疑问
高洛峰
高洛峰 2017-04-18 10:49:20
0
3
660

Java:在集合的遍历中,方法之一为 可以调用Collection接口中的 Object[] toArray()方法 将集合转为数组。这里为什么用 Object[]类型来当返回值,感觉有点怪

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
巴扎黑

1.Object is the parent class of all objects.
2. When the container class does not know what type will be put in, the implementation design can only use an Object array to store elements.
3. Generics are erased after compilation. In other words, for the JVM, what he sees is Object.
So only Object array can be returned. As for adding generics, the compiler will help you with casts and element detection.

PHPzhong

Yeah, weird.

So it is recommended to use Collection.toArray(T[] a) to return generics to avoid the problem of forced conversion of Object[].

Ty80

Because we don’t know the specific type of elements in the collection. And Object is the parent class of all classes. This is more reasonable.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!