Java List toArray(T [] a)的实现 [英] Java List toArray(T[] a) implementation

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

问题描述


返回一个数组,其中包含此列表中的所有元素。正确的顺序;返回数组的运行时类型是指定数组的运行时类型。如果列表符合指定的数组,则返回其中。否则,将使用指定数组的运行时类型和此列表的大小分配一个新数组。
如果列表符合指定的数组并且有空余空间(即数组的元素多于列表),紧接在集合结尾后的数组中的元素将设置为null。只有在调用者知道列表中不包含任何空元素时,这对确定列表的长度很有用。

 < ; T> T [] toArray(T [] a); 


我只是想知道为什么这样执行,基本上如果你传递一个长度为<到list.size(),它会简单地创建一个新的并返回它。因此,在方法参数中创建新的Array对象是无用的。



另外,如果使用列表的大小传递一个足够长的数组(如果返回相同的对象与对象 - 真的没有意义返回它,因为它是相同的对象,但为清晰起见。



问题是,我认为这会促进稍微低​​效的代码,在我的意见toArray应该简单地接收该类,并只返回新的数组与内容。



有没有任何理由为什么它不是这样编码?

解决方案

正如其他人所说,有几个不同的原因: b

  • 您需要以某种方式传入类型,并传入指定类型的数组并不是一种不合理的方式。无可否认,如果有一个版本是你想要的类型传递的,那么速度可能会很好。

  • 如果你想重用你的数组,你可以继续传递在同一个,而不是每次都需要创建一个新的。这可以节省时间和内存,以及GC问题,如果您需要多次,多次地完成这些操作


  • I was just looking at the method defined in the List interface:

    Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.

    <T> T[] toArray(T[] a);
    

    And I was just wondering why is it implemented this way, basically if you pass it an array with a length < to the list.size(), it will simply create a new one and return it. Therefore the creation of the new Array Object in the method parameter is useless.

    Additionally if you pass it an array long enough using the size of the list if returns that same object with the objects - really no point in returning it since it is the same object but ok for clarity.

    The problem is that I think this promotes slightly inefficient code, in my opinion toArray should simply receive the class and just return the new array with the contents.

    Is there any reason why it is not coded that way?.

    解决方案

    As mentioned by others, there are a couple different reasons:

    • You need to pass in the type somehow, and passing in an array of the specified type isn't an unreasonable way to do it. Admittedly, it might be nice if there was a version that you pass in the Class of the type you want too, for speed.
    • If you want to reuse your array, you can keep passing in the same one, rather than needing to create a new one each time. This can save time and memory, and GC issues if you need to do it many, many times

    这篇关于Java List toArray(T [] a)的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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