初始化ArrayList集合的方式有几种?可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
概述
ArrayList是一个以动态数组为基础实现的非线程安全的集合,ArrayList的元素可以为空、可以重复,同时又是有序的(读取和存放的顺序一致 )。
ArrayList继承AbstractList,实现了List
、RandomAccess
(可以快速访问)、Cloneable
(可以被克隆)、java.io.Serializable
(支持序列化)
ArrayList的初始化方式有三种:
1、无参构造,默认长度为10,是我们使用的最多的一种初始化方式:
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
这个时候,我们从源码中可以看到,里面只有一行代码:this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA,那么定义的DEFAULTCAPACITY_EMPTY_ELEMENTDATA可以在源码中找到:
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
通过注释可以得知,源码中定义了一个空的数组作为默认的大小,并且在第一个元素添加进来的时候再确定把数组扩充多少,这段逻辑会在接下来添加元素部分作出解释。
2、指定初始化长度:
/**
* Constructs an empty list with the specified initial capacity.
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
}
}
3、用一个Collection对象来构造
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
看完上述内容,你们对初始化ArrayList集合的方式有进一步的了解吗?如果还想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。