本文共 2035 字,大约阅读时间需要 6 分钟。
这是一道有赞的面试题,JDK源码中的内容,了解一下对自己也没坏处。
一般新建ArrayList
//DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {} //相当于new ArrayList(0) public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } 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); } }
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
add方法
ensureCapacityInternal方法与ensureExplicitCapacity是确保数组扩容到指定的大小
private void grow(int minCapacity) { //之前的容量 int oldCapacity = elementData.length; //新的容量为之前的容量 1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); //如果新的容量小于 要扩容的容量,新的容量等于要扩容的容量 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: elementData = Arrays.copyOf(elementData, newCapacity); }
arraylist的源码还行吧,想要理解的更深,多做些实验才行。
转载地址:http://rtyto.baihongyu.com/