gpt4 book ai didi

java - toArray(T[] a) 和 toArray() 之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:30 29 4
gpt4 key购买 nike

我一直在学习如何使用 java 进行编程,但对于 LinkedListtoArray(T[] a) 的区别我还没有得到任何明确的解释和 toArray() 方法。第二个简单地将 LinkedList 对象中的所有元素作为数组返回,对吧?但是,第一个呢?

编辑:

我的意思是,我阅读了 oracle 的文档,它说:

Returns an array containing all of the elements in this list in proper sequence (from first to last element); 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 list 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.)

Like the toArray() method, this method acts as bridge between array-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs.

我不明白加粗显示的句子的意思。

最佳答案

假设您有一个 List<String> ,并且您想将其转换为 String[] .让我们看看两种方法的工作原理:

List<String> source = new LinkedList<String>();
// Fill in some data

Object[] array1 = source.toArray();
String[] array2 = source.toArray(new String[source.size()]);

看出区别了吗?第一个简单地创建一个 Object[] ,因为它不知道类型参数的类型 <T> ,而第二个只是填满了 String[]你通过了(这是你想要的)。您几乎总是需要使用第二种方法。

关于java - toArray(T[] a) 和 toArray() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392705/

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