ArrayList.toArray()的Java方法 [英] ArrayList.toArray() method in Java

查看:135
本文介绍了ArrayList.toArray()的Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么他们设计了的toArray 方法的ArrayList 采取Java中的数组的输入?

I am wondering why did they design the toArray method in ArrayList to take a input of an array in Java?

    ArrayList<String> listArray = new ArrayList<String>();

    listArray.add("Germany");
    listArray.add("Holland");
    listArray.add("Sweden");

    String []strArray = new String[3];
    String[] a = (String [])listArray.toArray(strArray);

要我看来,他们不需要此输入,因为ArrayList的实例本身有足够的细节来将数据转换成一个数组。

To me it appears that, they dont need this input because the instance of the ArrayList itself has enough details to convert the data into an array.

我的问题是,为什么他们仍然需要数组进行传递?谢谢你。

My question is why do they still need the array to be passed in? Thanks.

推荐答案

有两个原因,我能想到的:

Two reasons I can think of:


  1. 擦除意味着泛型参数不能在运行时可用,所以一个的ArrayList&LT;弦乐&GT; 不的知道的,它包含字符串,它只是原始类型的ArrayList 。因此,的toArray所有调用()将不得不返回对象[] ,这是不完全正确。你必须真正创造的第二个阵列的String [] 然后遍历第一,铸造其所有又将参数来与期望的结果类型。

  2. 定义方法的方式意味着你可以到现有的数组的引用传递,并且必须通过这个方法填充。在某些情况下,这可能是很方便的,而不是一个新的数组返回,然后在其他地方复制其值。

  1. Erasure means that the generic parameters aren't available at runtime, so an ArrayList<String> doesn't know that it contains strings, it's just the raw type ArrayList. Thus all invocations of toArray() would have to return an Object[], which isn't strictly correct. You'd have to actually create a second array of String[] then iterate over the first, casting all of its parameters in turn to come out with the desired result type.
  2. The way the method is defined means that you can pass in a reference to an existing array, and have this populated via the method. In some cases this is likely very convenient, rather than having a new array returned and then copying its values elsewhere.

这篇关于ArrayList.toArray()的Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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