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.

This means that the programmer is in control over what type of array it should be.

For example, for your ArrayList<Integer> instead of an Integer[] array you might want a Number[] or Object[] array.

Furthermore, the method also checks the array that is passed in. If you pass in an array that has enough space for all elements, the the toArray

method re-uses that array. This means:

Integer[] myArray = new Integer[myList.size()];
myList.toArray(myArray);

or

Integer[] myArray = myList.toArray(new Integer[myList.size()]);

has the same effect but is more efficient than

Integer[] myArray = myList.toArray(new Integer[0]);

as the latter operation uses reflection to check the array type and then dynamically construct an array of the right type. By passing in a correctly

sized array in the first place, reflection does not have to be used to allocate a new array inside the toArray method.

    /**
* {@inheritDoc}
*
* <p>This implementation returns an array containing all the elements
* returned by this collection's iterator in the same order, stored in
* consecutive elements of the array, starting with index {@code 0}.
* If the number of elements returned by the iterator is too large to
* fit into the specified array, then the elements are returned in a
* newly allocated array with length equal to the number of elements
* returned by the iterator, even if the size of this collection
* changes during iteration, as might happen if the collection permits
* concurrent modification during iteration. The {@code size} method is
* called only as an optimization hint; the correct result is returned
* even if the iterator returns a different number of elements.
*
* <p>This method is equivalent to:
*
* <pre> {@code
* List<E> list = new ArrayList<E>(size());
* for (E e : this)
* list.add(e);
* return list.toArray(a);
* }</pre>
*
* @throws ArrayStoreException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
// Estimate size of array; be prepared to see more or fewer elements
int size = size();
T[] r = a.length >= size ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), size);
Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) { // fewer elements than expected
if (a == r) {
r[i] = null; // null-terminate
} else if (a.length < i) {
return Arrays.copyOf(r, i);
} else {
System.arraycopy(r, 0, a, 0, i);
if (a.length > i) {
a[i] = null;
}
}
return a;
}
r[i] = (T)it.next();
}
// more elements than expected
return it.hasNext() ? finishToArray(r, it) : r;
}

Java List <T> T[] toArray(T[] a) implementation的更多相关文章

  1. java关于ArrayList中toArray方法的使用

    先来看下面这段程序 Collection collect= new ArrayList();   collect.add("小黑");   collect.add("小白 ...

  2. 【Java】ArrayList 的 toArray() 方法抛出 ClassCastException 异常

    第一次用这个方法,结果冒出个莫名其妙的异常来: String[] names = (String[]) mTags.toArray(); 结果会抛出 java.lang.ClassCastExcept ...

  3. java中List的toArray方法

    把List转换成某种类型的数组,就拿String类型来做例子吧,有以下两种方式: //方法1,使用不带参数的toArray方法 String[] arr1=new String[list.size() ...

  4. Java系列:Collection.toArray用法研究

    该方法的签名如下: <T> T[] Collection.toArray(T[] arrayToFill); 这里想验证两个问题: 1)arrayToFill什么时候会被填充: 2)arr ...

  5. Java SCP copy local file to remote implementation

    最近做的项目中,有一个小需求,需要通过SCP把本地文件copy到远程服务器.查了好多资料,最终解决方案简单快速,分享一下. 在这里,需要用到4个jar包,分别是ant-jsch.jar,ant-lau ...

  6. 【Java集合系列二】LinkedList解析

    一.简介 1.LinkedList继承关系 2.LinkedList底层实现 LinkedList使用双向链表存储数据,所以没有默认的容量,也不会有扩容一说.只有两个指针,永远指向链表的两端:firs ...

  7. Java Knowledge series 7

    Pepole who make a greate contribution on common libaraies deserve our respect. Component(Widget) / S ...

  8. [转载]Java 8 日期&时间 API

    Java 8 日期和时间 声明 本文转自http://www.journaldev.com/2800/java-8-date-localdate-localdatetime-instant,以mark ...

  9. Java DNS查询内部实现

    源码分析 在Java中,DNS相关的操作都是通过通过InetAddress提供的API实现的.比如查询域名对应的IP地址: String dottedQuadIpAddress = InetAddre ...

随机推荐

  1. [Vim] 搜索模式(正则表达式)

    本文介绍如何使用Vim的搜索模式. 搜索单词 Vim中使用 \< 和 \> 分别表示单词的开头和结尾,例如查找单词 i 而不是字母 i ,在正常模式下,按下 / 启动搜索模式,输入 \&l ...

  2. java 递归

    package com.j1.soa.resource.cms.service.oracle; import com.j1.base.dto.ServiceMessage; import com.j1 ...

  3. 二叉查找树(BST)的性质

    二叉查找树的性质: 1.左子树上所有结点的值均小于或等于它的根结点的值. 2.右子树上所有结点的值均大于或等于它的根结点的值. 3.左.右子树也分别为二叉排序树. 下图中这棵树,就是一颗典型的二叉查找 ...

  4. JS函数匿名替换

    //匿名替换函数 function objFunc() { var obj = new Object(); obj.JsonData = [{ aa: "}], obj.FilterData ...

  5. numpy常用举例

    转自https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-1-np-attributes/ numpy 的属性: ndim: ...

  6. MDU某产品OMCI模块代码质量现状分析

    说明 本文参考MDU系列某产品OMCI模块现有代码,提取若干实例以说明目前的代码质量,亦可作为甄别不良代码的参考. 本文旨在就事论事,而非否定前人(没有前人的努力也难有后人的进步).希望以史为鉴,不破 ...

  7. 在本机搭建mycat 单机环境,使用mariadb 伪集群

    首先搭建mairadb的集群 master 使用端口3306 slave 使用端口3406 master 相关配置 在my.ini 文件的[mysqld] 节点中添加或修改如下配置 #允许其他机器re ...

  8. 【大数据系列】在windows下连接linux 下的hadoop环境进行开发

    一.下载Eclipse并安装 二.下载exlipse的hadoop plugin 三.打开Map Reduce视图 Window --> Perspective --> Open pers ...

  9. 使用 mysql workbench 建议

    在日常使用mysql workbench时,未免操作失误,不建议启用远程管理.

  10. 部署OpenStack问题汇总(一)--使用packstack安装openstack:源问题的处理

    在安装的过程中,遇到了源的问题,找不到包的网页:    重新打开 预装源地址,打开epel-openstack-havana.repo 文件,显示如下: # Place this file in yo ...