标签:
java.util.ArrayList就是传说中的动态数组.
继承了关系,有此可看出ArrayList与list的collection的关系
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
分析期特性
具有实例化性质,从实现了serializable就可以看出来
private static final long serialVersionUID = 8683452581122892189L;
接下来定义了初始容量大小,和初始锥形。arralist里面本身存储的为一个Object类型的数组
/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; private transient Object[] elementData;
使用arraylist时需要实例化:有三种
/** * 初始化一个给定大小容量的数组List,主要用于如果本事知道这个list的大小时。 * 能优化如果大小超过默认容量时导致arralist每次都要去增加并创建一个新的list * @param initialCapacity the initial capacity of the list * @throws 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 */ public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } /** * 根据一个collection来定义一个arralist * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ 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); }
Arraylist有提供期可能存在过多的空容量时清除处理
public void trimToSize() { modCount++; if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } }
另一个知识点。当arraylist新增时如果当前容量已满时的处理过程
public boolean add(E e) { ensureCapacityInternal(size + 1); // 判断容量是否超标 elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == 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); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // 容量大小 int newCapacity = oldCapacity + (oldCapacity >> 1); //超标增加量计算法,x+x/2=50%左右 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // 赋值原来的数组,并增加newCapacity个容量 elementData = Arrays.copyOf(elementData, newCapacity); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
标签:
原文地址:http://www.cnblogs.com/hwaggLee/p/4509030.html