其他分享
首页 > 其他分享> > ArrayList中的toArray方法

ArrayList中的toArray方法

作者:互联网

JDK中 toArray 由两个,一个有参一个无参,下面说的主要是有参函数。首先看源码

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 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.)
Params:
a – the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Returns:
an array containing the elements of the list
Throws:
ArrayStoreException – if the runtime type of the specified array is not a supertype of the runtime type of every element in this list
NullPointerException – if the specified array is null

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    if (a.length < size)
        // Make a new array of a's runtime type, but my contents:
        return (T[]) Arrays.copyOf(elementData, size, a.getClass());
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

它的参数是一个数组,方法的功能就是把链表中的元素变成数组的元素,这里的参数 a 就是处理后元素所在的容器。如果提供的 a 的容量小于 ArrayList 的长度,那么就会把 a 扩容到刚好容下所有元素;如果容量足够大的话就直接把链表中的元素拷到数组中,并把数组中没有盛方元素的第一个位置的值为null,表示数组结束(逻辑上)。

标签:toArray,type,ArrayList,list,specified,array,runtime,方法,size
来源: https://www.cnblogs.com/klaus08/p/15186821.html