Java List <T> T[] toArray(T[] a) implementation
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的更多相关文章
- java关于ArrayList中toArray方法的使用
先来看下面这段程序 Collection collect= new ArrayList(); collect.add("小黑"); collect.add("小白 ...
- 【Java】ArrayList 的 toArray() 方法抛出 ClassCastException 异常
第一次用这个方法,结果冒出个莫名其妙的异常来: String[] names = (String[]) mTags.toArray(); 结果会抛出 java.lang.ClassCastExcept ...
- java中List的toArray方法
把List转换成某种类型的数组,就拿String类型来做例子吧,有以下两种方式: //方法1,使用不带参数的toArray方法 String[] arr1=new String[list.size() ...
- Java系列:Collection.toArray用法研究
该方法的签名如下: <T> T[] Collection.toArray(T[] arrayToFill); 这里想验证两个问题: 1)arrayToFill什么时候会被填充: 2)arr ...
- Java SCP copy local file to remote implementation
最近做的项目中,有一个小需求,需要通过SCP把本地文件copy到远程服务器.查了好多资料,最终解决方案简单快速,分享一下. 在这里,需要用到4个jar包,分别是ant-jsch.jar,ant-lau ...
- 【Java集合系列二】LinkedList解析
一.简介 1.LinkedList继承关系 2.LinkedList底层实现 LinkedList使用双向链表存储数据,所以没有默认的容量,也不会有扩容一说.只有两个指针,永远指向链表的两端:firs ...
- Java Knowledge series 7
Pepole who make a greate contribution on common libaraies deserve our respect. Component(Widget) / S ...
- [转载]Java 8 日期&时间 API
Java 8 日期和时间 声明 本文转自http://www.journaldev.com/2800/java-8-date-localdate-localdatetime-instant,以mark ...
- Java DNS查询内部实现
源码分析 在Java中,DNS相关的操作都是通过通过InetAddress提供的API实现的.比如查询域名对应的IP地址: String dottedQuadIpAddress = InetAddre ...
随机推荐
- Python系统编程笔记
01. 进程与程序 编写完毕的代码,在没有运行的时候,称之为程序 正在运行着的代码,就称为进程 进程是系统分配资源的最小单位. 进程资源包括: 中间变量 代码 计数器 02. 通过os.fork()函 ...
- java的两种冒泡算法
所谓的冒泡算法,就是给数组进行排序,可以根据以小到大的顺序,也可以根据以小到大的顺序,在数组的封装类java.util.Arrays通过sort方法进行按升序的排序.那不用类的话怎么进行呢? 思路一: ...
- bool和BOOL类型知识集合
知识点一.C语言中有bool类型吗? 转自http://blog.csdn.net/liuqiqi677/article/details/6703615 之前一直都没有注意到,最近在用C语言写DSP算 ...
- Android使用Handler造成内存泄露的分析及解决方法
一.什么是内存泄露? Java使用有向图机制,通过GC自动检查内存中的对象(什么时候检查由虚拟机决定),如果GC发现一个或一组对象为不可到达状态,则将该对象从内存中回收.也就是说,一个对象不被任何引用 ...
- MFC控件CTabCtrl关联变量
1.先建立一个对话框MFC应用程序,然后在工具箱里面把Tab Control控件放到对话框中的合适位置上. 再在对话框类中,将该控件绑定一个变量 用两种方法: 1 ) 自己定义成员变量 CTabCtr ...
- ubuntu 14.04 LTS 右键菜单解压压缩包时出错
先卸载rar sudo apt-get remove rar 再安装unrar sudo apt-get install unrar
- 题目1008:最短路径问题(最短路径问题dijkstra算法)
题目链接:http://ac.jobdu.com/problem.php?pid=1008 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...
- CF 445A DZY Loves Chessboard
A. DZY Loves Chessboard time limit per test 1 second memory limit per test 256 megabytes input stand ...
- 【转】详解抓取网站,模拟登陆,抓取动态网页的原理和实现(Python,C#等)
转自:http://www.crifan.com/files/doc/docbook/web_scrape_emulate_login/release/html/web_scrape_emulate_ ...
- Dockerfile创建镜像
Dockerfile是一个文本格式的配置文件,用户可以使用Dockerfile来快速创建自定义的镜像. Dockerfile由一行行命令语句组成,并且支持易#开头的注释行. 一般而言Dockerfil ...