ArrayList分析
1.ArrayList底层数据结构是一个动态数组。
源码中的定义为:transient Object[] elementData; 还定义了数组的大小private int size;
集合的三个构造方法:
第一个: 带有集合初始化大小的构造方法
1 public ArrayList(int initialCapacity) { 2 if (initialCapacity > 0) { 3 this.elementData = new Object[initialCapacity]; 4 } else if (initialCapacity == 0) { 5 this.elementData = EMPTY_ELEMENTDATA; 6 } else { 7 throw new IllegalArgumentException("Illegal Capacity: "+ 8 initialCapacity); 9 } 10 }
第二个:空构造方法
1 public ArrayList() { 2 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; 3 }
第三个:通过集合的构造方法
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
ArrayList集合底层为动态数组,很多方法都是基于数组的底层下实现的,而这里实现动态数组的扩容1.5倍是这个集合动态构建的方法,直接上jdk源码
//简单分析ensureCapacity:确保容量,通过minExpand来记录当前的容量,通过传入minCapacity来判断是否需要扩展容量
public void ensureCapacity(int minCapacity) { int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY;
if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } }
//直接调用ensureExplicitCapacity方法 private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
//扩容处理,通过if进一步确认是否真的需要扩容 private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
//这个变量,是VMs存储了些头信息在里面,源码注释是这么说具体也不是特别了解为什么要少8. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//真正的动态增长,newCapacity = oldCapacity + (oldCapacity >> 1);实现增长1.5倍,位运算通过右移一位。ps:位运算应该是各种运算中速度最快的了 private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; 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); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
剩下的那些ArrayList的方法其实和普通的操作数组的方法都是一样的,大家直接看源码就可以很简单的了解到了,这里就不重复了╮(╯_╰)╭
这里还是要提一下的,ArrayList是非线程安全,所以多线程同时修改ArrayList集合的时候,及其有可能发生错误,如果要多线程环境实现,就使用vector集合