直接上源码:
构造函数:
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); }
其实arrayList的本质是一个数据,只不过这个数组的大小可以变化。我们先来看下arraylist的数组是怎么定义的
/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @exception IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; }
构造函数直接弄了一个10大小的obj对象数组。
this.elementData = new Object[initialCapacity];
讲到这里我们看下其实只有两个成员变量:
private static final long serialVersionUID = 8683452581122892189L; /** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. */ private transient Object[] elementData;//元素 /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;//list元素数量
看他的核心方法:add
public boolean add(E e) { ensureCapacity(size + 1); // 添加元素的时候先让数量+1 elementData[size++] = e;//对应的数组引用放对应的对象 return true; }
这里面有个比较有意思的方法就是这个ensureCapacit这个方法里面有对应的扩展数组的算法:
public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length;//获得最初的数组大小,默认情况下初始值是10 if (minCapacity > oldCapacity) {//如果比原先的数组元素大了执行如下操作 Object oldData[] = elementData;//保存原有的数组元素 //重新new一个数组 int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: //重新生成一个数组对象并返回,生成的数组对象大小为原先的1.5X+1和minCapacity之间较大的那个 elementData = Arrays.copyOf(elementData, newCapacity); } }
jdk源码解读之ArrayList
时间: 2024-10-01 07:30:56