ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ArrayList中的toArray方法

2021-08-25 20:31:43  阅读:206  来源: 互联网

标签:toArray type ArrayList list specified array runtime 方法 size


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有