Java 集合系列(二)—— ArrayList

  ArrayList 是通过一个数组来实现的,因此它是在连续的存储位置存放对象的引用,只不过它比 Array 更智能,能够根据集合长度进行自动扩容。

 

  假设让我们来实现一个简单的能够自动扩容的数组,我们最容易想到的点就是:

add()的时候需要判断当前数组size+1是否等于此时定义的数组大小;

若小于直接添加即可;否则,需要先扩容再进行添加。

实际上,ArrayList的内部实现原理也是这样子,我们可以来研究分析一下ArrayList的源码

 add(E e) 源码分析

1 /** 2 * Appends the specified element to the end of this list. 3 * 4 * @param e element to be appended to this list 5 * @return <tt>true</tt> (as specified by {@link Collection#add}) 6 */ 7 public boolean add(E e) { 8 ensureCapacityInternal(size + 1); // 进行扩容校验 9 elementData[size++] = e; // 将值添加到数组后面,并将 size+1 10 return true; 11 } 12 13 14 15 /** 16 * The array buffer into which the elements of the ArrayList are stored. 17 * The capacity of the ArrayList is the length of this array buffer. Any 18 * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 19 * will be expanded to DEFAULT_CAPACITY when the first element is added. 20 */ 21 transient Object[] elementData; // non-private to simplify nested class access 22 23 private void ensureCapacityInternal(int minCapacity) { 24 ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); // elementData 数组 25 } 26 27 28 29 /** 30 * Default initial capacity. 31 */ 32 private static final int DEFAULT_CAPACITY = 10; 33 34 /** 35 * Shared empty array instance used for default sized empty instances. We 36 * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when 37 * first element is added. 38 */ 39 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; 40 41 // 返回最大的 index 42 private static int calculateCapacity(Object[] elementData, int minCapacity) { 43 if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 与空数组实例对比 44 return Math.max(DEFAULT_CAPACITY, minCapacity); 45 } 46 return minCapacity; 47 } 48 49 50 51 private void ensureExplicitCapacity(int minCapacity) { 52 modCount++; 53 54 // overflow-conscious code 55 if (minCapacity - elementData.length > 0) 56 grow(minCapacity); 57 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zydpyz.html