ArrayList
1.动态数组
2.线程不安全
3.存储空间连续
4.查询快,添加删除慢
- 构造方法
/** + 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 = {}; /** + Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }这个构造方法很简单,初始化了一个空的elementData,并没有赋予数组长度
- 元素添加
/** + Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; /** + 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA + will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access /** + The size of the ArrayList (the number of elements it contains). * + @serial */ private int size; /** + Appends the specified element to the end of this list. * + @param e element to be appended to this list + @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { // 首先进行扩充 ensureCapacityInternal(size + 1); // Increments modCount!! // 将元素追加到最后 elementData[size++] = e; return true; } // 扩充 private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } // 计算数组大小 第一次调用此处的elementData={},所以返回值为DEFAULT_CAPACITY=10,也就是默认的数组长度是10 private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) // 当加上当前元素后的集合长度(size)大于现在数组长度(elementData.length)在进行扩充 grow(minCapacity); } // 真正的扩充操作 private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // 此处oldCapacity=0 int newCapacity = oldCapacity + (oldCapacity >> 1); // 此处newCapacity=0 if (newCapacity - minCapacity < 0) // 此处minCapacity=10 newCapacity = minCapacity; // 此处newCapacity=10 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); //数组拷贝 } 真正的数组长度是在第一次添加的时候进行初始化的,默认为10
最主要的消耗是在扩容(数组拷贝)
当集合长度大于数组长度的时候进行扩充,扩充的标准是1.5倍[oldCapacity + (oldCapacity >> 1)]
- 查询
public E get(int index) { rangeCheck(index);// 校验 return elementData(index); } E elementData(int index) { return (E) elementData[index]; }Vector
1.动态数组,类似于ArrayList
2.线程安全
3.消耗大
- 构造方法
public Vector
