本文主要记录arraylist存储数据的方式
- 以下图为例
public static void main(String[] args) {
//构造一个arraylist对象
ArrayList list = new ArrayList<>();
//循环添加数据 0-9
for (int i = 0; i<10;i++){
list.add(i);
}
//打印输出数据
System.out.println(list);
}
- ArrayList list = new ArrayList<>();——调用下列方法
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//给不会被序列化的数组赋空值
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
}
2. list.add(i);——调用下列方法
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//为集合添加元素
public boolean add(E e) {
//确保数组空间充足
ensureCapacityInternal(size + 1); // Increments modCount!!
//为当前顺序下标指定值
elementData[size++] = e;
return true;
}
}
ensureCapacityInternal(size +1);
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private void ensureCapacityInternal(int minCapacity) {
//返回当前所需最小数组长度,如果数组为空,给数组长度10。
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
}
ensureExplicitCapacity
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private void ensureExplicitCapacity(int minCapacity) { //记录操作次数 modCount++;
<span class="hljs-comment">// overflow-conscious code <span class="hljs-comment">/*判断如果最小所需数组空间 - 当前数组的长度 > 0 调用grow方法为数组扩容 */ <span class="hljs-keyword">if (minCapacity - elementData.length > <span class="hljs-number">0) grow(minCapacity); }
}
grow(minCapacity)
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//为数组扩容
private void grow(int minCapacity) {
// overflow-conscious code
//取得当前数组的长度
int oldCapacity = elementData.length;
/*获取数组扩容后的长度 oldCapacity >> 1 = oldCapacity / 2
扩容后的长度为原数组长度的1.5倍
*/
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果扩容后的长度-数组需要的最小长度<0 ,将minCapacity置为扩容后的长度
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果达到数组最大长度执行
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
//将原数组数据拷贝到扩容后的数组中,空闲空间值为null
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
最后回到add方法为当前下标赋值
//为当前顺序下标指定值
elementData[size++] = e;
END