为什么List.toArray()返回Object的数组? [英] Why does List.toArray() return an array of Object?

查看:403
本文介绍了为什么List.toArray()返回Object的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


查看此代码示例:

  List< String> list = new ArrayList< String>(); 
list.add(hello);
list.add(world);
Object [] array = list.toArray();

为什么方法 toArray() return Object 的数组?其他列表方法如 get() remove() $

 因为数组已经存在,所以可以返回列表中的对象类型。

解决方案自从开始就在Java中,而泛型
仅在Java 5中引入。List.toArray()方法是在Java 1.2中引入的
,在泛型存在之前,因此它是
指定的返回Object []。

可以使用 toArray(T [] a)只需查看 Collection.toArray(T [] a)


Possible Duplicate:
why does List<String>.toArray() return Object[] and not String[]? how to work around this?

See this code example :

    List<String> list = new ArrayList<String>();
    list.add("hello");
    list.add("world");
    Object [] array = list.toArray();

Why does the method toArray() return an array of Object ? Other List methods such as get() , remove() are able to return the type of objects in the list.

解决方案

Because array has been in Java since the beginning, while generics
were only introduced in Java 5. And the List.toArray() method was 
introduced in Java 1.2, before generics existed, so it was
specified to return Object[].

u can use toArray(T[] a) just take a look Collection.toArray(T[] a)

这篇关于为什么List.toArray()返回Object的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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