gpt4 book ai didi

Java List toArray(T[] a) 实现

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:28 25 4
gpt4 key购买 nike

我只是在看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);

我只是想知道为什么要这样实现,基本上如果你将一个长度为 < 的数组传递给 list.size(),它只会创建一个新数组并返回它。因此在方法参数中创建新的数组对象是没有用的。

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

问题是我认为这会导致代码效率稍低,在我看来 toArray 应该简单地接收类并返回包含内容的新数组。

有什么理由不这样编码吗?

最佳答案

  357       public <T> T[] toArray(T[] a) {
358 if (a.length < size)
359 // Make a new array of a's runtime type, but my contents:
360 return (T[]) Arrays.copyOf(elementData, size, a.getClass());
361 System.arraycopy(elementData, 0, a, 0, size);
362 if (a.length > size)
363 a[size] = null;
364 return a;
365 }

也许它有一个运行时类型?

来自维基:

Consequently, instantiating a Java class of a parameterized type is impossible because instantiation requires a call to a constructor, which is unavailable if the type is unknown.

关于Java List toArray(T[] a) 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6542242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com