前言
基于Java1.8源码,层级结构就不再多叙述,只介绍几个内部方法解析
主要属性
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*
* Package private to allow access from java.util.Collections.
*/
transient Object[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
解析:EMPTY_ELEMENTDATA
属性,从注释上看就是提供一个默认的空的数组;elementData
一个数组,里面存放的集合里面的所有数据 size
不做叙述了,大家都懂。
构造方法解析
//构造方法1 传入初始化 elementData容量,并创建一个容量为initialCapacity大小的数组
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/** 构造方法2 默认构造一个容量为10的数组
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
//构造方法3 传入一个Collection的实现类(很多,List Set都是)就做了2步操作 数据的赋值和一步校验,校验代码可以去看Arrays这个类
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
几个主要的和常用的方法
public boolean contains(Object o) {
return indexOf(o) >= 0;
}