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. flask文件上传

    #coding=utf-8 import os from flask import Flask from flask import request from flask import redirect ...

  2. warning C4305:“初始化”:从“double”到“float”截断

    编译VS项目时出现警告: warning C4305:“初始化”:从“double”到“float”截断(warning C4305: 'initializing' : truncation from ...

  3. php curl那点事儿

    curl是最常用功能之一初始化句柄 $ch = curl_init(); post 传$data 1. 如果$data是字符串,则Content-Type是application/x-www-form ...

  4. iOS - 扩展UIButton的响应区域

    扩展UIButton的响应区域 引言 通常在iOS开发中通常会遇到产品说按钮的响应区域不大 而UI给我们的设计是按钮的面积 而不是按钮的响应面积 所以在这种情况下需要我们自己去扩展按钮的响应区域 思考 ...

  5. <转>特征工程(一)

    转自http://blog.csdn.net/han_xiaoyang/article/details/50481967 1. 引言 再过一个月就是春节,相信有很多码农就要准备欢天喜地地回家过(xia ...

  6. 在centos7 ubuntu15.04 上通过bosh-lite 搭建单机环境cloudfoundry

    Bosh-lite简介       bosh-lite 是一个单机部署cloudfoundry的实验性工具,用于开发人员做poc 验证.Bosh-lite目前支持仅MAC OS X和Linux系统.B ...

  7. 【WEB前端系列之CSS】CSS3动画之Animation

    前言 动画使用示例https://github.com/AndyFlower/web-front/tree/master/css3/loading 学习CSS3中Animation之前先来看一个动画特 ...

  8. es6 - class的学习

    http://es6.ruanyifeng.com/#docs/class:class Person { constructor{ //构造函数,里边放不被继承的私有属性和方法 this.proper ...

  9. JS-几大排序算法(更新中...)

    关于排序都会讲的名词:(我自己的理解) 时间复杂度: 指排序过程中,程序消耗的时间. 空间复杂度: 指排序过程中,程序所消耗内存的大小. 稳定: 如果两个值相等,a和b,a=b且a在b位置的左边,排序 ...

  10. Java中的一些性能监控和故障分析工具

    这些工具都在JDK的bin目录下,如果配置了java的环境变量,可以直接在命令行里调用这些小工具 jps 查看java进程信息 jstat java虚拟机状态监控工具 jstat -gc(或 -gcn ...