在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

给jdk写注释系列之jdk1.6容器(1)-ArrayList源码解析

2017-2-7 13:39| 发布者: zhangjf| 查看: 487| 评论: 0

摘要: public interface CollectionE extends IterableE { int size(); boolean isEmpty(); boolean contains(Object o); IteratorE iterator(); Object toArray(); T T toArray(T a); boolean add(E ...
  1. public interface Collection<E> extends Iterable<E> {
  2. int size();
  3. boolean isEmpty();
  4. boolean contains(Object o);
  5. Iterator<E> iterator();
  6. Object[] toArray();
  7. <T> T[] toArray(T[] a);
  8. boolean add(E e);
  9. boolean remove(Object o);
  10. boolean containsAll(Collection<?> c);
  11. boolean addAll(Collection<? extends E> c);
  12. boolean removeAll(Collection<?> c);
  13. boolean retainAll(Collection<?> c);
  14. void clear();
  15. boolean equals(Object o);
  16. int hashCode();
  17. }
复制代码

然后是接口List的定义,

  1. public interface List<E> extends Collection<E> {
  2. int size();
  3. boolean isEmpty();
  4. boolean contains(Object o);
  5. Iterator<E> iterator();
  6. Object[] toArray();
  7. <T> T[] toArray(T[] a);
  8. boolean add(E e);
  9. boolean remove(Object o);
  10. boolean containsAll(Collection<?> c);
  11. boolean addAll(Collection<? extends E> c);
  12. boolean addAll( int index, Collection<? extends E> c);
  13. boolean removeAll(Collection<?> c);
  14. boolean retainAll(Collection<?> c);
  15. void clear();
  16. boolean equals(Object o);
  17. int hashCode();
  18. E get( int index);
  19. E set( int index, E element);
  20. void add( int index, E element);
  21. E remove( int index);
  22. int indexOf(Object o);
  23. int lastIndexOf(Object o);
  24. ListIterator<E> listIterator();
  25. ListIterator<E> listIterator( int index);
  26. List<E> subList( int fromIndex, int toIndex);
  27. }
复制代码

再看下ArrayList的定义,

  1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
复制代码

可以看出ArrayList继承AbstractList(这是一个抽象类,对一些基础的list操作进行封装),实现List,RandomAccess,Cloneable,Serializable几个接口,RandomAccess是一个标记接口,用来表明其支持快速随机访问。

2.底层存储

顾名思义哈,ArrayList就是用数组实现的List容器,既然是用数组实现,当然底层用数组来保存数据啦。。。

  1. private transient Object[] elementData;
  2. private int size;
复制代码

可以看到用一个Object数组来存储数据,用一个int值来计数,记录当前容器的数据大小。

另外,细心的人会发现 elementData数组是使用 transient 修饰的,关于 transient 关键字的作用简单说就是 java自带默认机制进行序列化 的时候,被其修饰的属性不需要维持。会不会产生一点疑问? elementData不需要维持,那么怎么进行反序列化,又怎么保证序列化和反序列化数据的正确性?难道不需要存储?用大腿想一下那当然是不可以的嘛,既然需要存储,它是怎么实现的呢?注意上面红色加粗的地方,默认序列化机制,嗯哼想明白了ArrayList一定是使用了自定义的序列化方式,到底是不是这样的呢?看下面两个方法:

  1. /**
  2. * Save the state of the <tt>ArrayList</tt> instance to a stream (that
  3. * is, serialize it).
  4. *
  5. * @serialData The length of the array backing the <tt>ArrayList </tt>
  6. * instance is emitted (int), followed by all of its elements
  7. * (each an <tt>Object</tt> ) in the proper order.
  8. */
  9. private void writeObject(java.io.ObjectOutputStream s)
  10. throws java.io.IOException{
  11. // Write out element count, and any hidden stuff
  12. int expectedModCount = modCount ;
  13. s.defaultWriteObject();
  14. // Write out array length
  15. s.writeInt( elementData.length );
  16. // Write out all elements in the proper order.
  17. for (int i=0; i<size; i++)
  18. s.writeObject( elementData[i]);
  19. if (modCount != expectedModCount) {
  20. throw new ConcurrentModificationException();
  21. }
  22. }
  23. /**
  24. * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
  25. * deserialize it).
  26. */
  27. private void readObject(java.io.ObjectInputStream s)
  28. throws java.io.IOException, ClassNotFoundException {
  29. // Read in size, and any hidden stuff
  30. s.defaultReadObject();
  31. // Read in array length and allocate array
  32. int arrayLength = s.readInt();
  33. Object[] a = elementData = new Object[arrayLength];
  34. // Read in all elements in the proper order.
  35. for (int i=0; i<size; i++)
  36. a[i] = s.readObject();
  37. }
复制代码

英语注释很详细,也很容易读懂,就不进行翻译了。那么想一下为什么要这样设计呢,岂不是很麻烦。下面简单进行解释下:

elementData 是一个数据存储数组,而数组是定长的,它会初始化一个容量,等容量不足时再扩充容量(扩容方式为数据拷贝,后面会详细解释),再通俗一点说就是比如 elementData 的长度是10,而里面只保存了3个对象,那么数组中其余的7个元素(null)是没有意义的,所以也就不需要保存,以节省序列化后的内存容量,好了到这里就明白了这样设计的初衷和好处,顺便好像也明白了长度单独用一个int变量保存,而不是直接使用 elementData.length的原因。

3.构造方法

  1. /**
  2. * 构造一个具有指定容量的list
  3. */
  4. public ArrayList( int initialCapacity) {
  5. super();
  6. if (initialCapacity < 0)
  7. throw new IllegalArgumentException( "Illegal Capacity: " +
  8. initialCapacity);
  9. this.elementData = new Object[initialCapacity];
  10. }
  11. /**
  12. * 构造一个初始容量为10的list
  13. */
  14. public ArrayList() {
  15. this(10);
  16. }
  17. /**
  18. * 构造一个包含指定元素的list,这些元素的是按照Collection的迭代器返回的顺序排列的
  19. */
  20. public ArrayList(Collection<? extends E> c) {
  21. elementData = c.toArray();
  22. size = elementData .length;
  23. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  24. if (elementData .getClass() != Object[].class)
  25. elementData = Arrays.copyOf( elementData, size , Object[].class);
  26. }
复制代码

构造方法看完了,想一下指定容量的构造方法的意义,既然默认为10就可以那么为什么还要提供一个可以指定容量大小的构造方法呢?在这里说好像有点太早,那就卖个关子,下面再说 。。 。

4.增加

  1. /**
  2. * 添加一个元素
  3. */
  4. public boolean add(E e) {
  5. // 进行扩容检查
  6. ensureCapacity( size + 1); // Increments modCount
  7. // 将e增加至list的数据尾部,容量+1
  8. elementData[size ++] = e;
  9. return true;
  10. }
  11. /**
  12. * 在指定位置添加一个元素
  13. */
  14. public void add(int index, E element) {
  15. // 判断索引是否越界,这里会抛出多么熟悉的异常。。。
  16. if (index > size || index < 0)
  17. throw new IndexOutOfBoundsException(
  18. "Index: "+index+", Size: " +size);
  19. // 进行扩容检查
  20. ensureCapacity( size+1); // Increments modCount
  21. // 对数组进行复制处理,目的就是空出index的位置插入element,并将index后的元素位移一个位置
  22. System. arraycopy(elementData, index, elementData, index + 1,
  23. size - index);
  24. // 将指定的index位置赋值为element
  25. elementData[index] = element;
  26. // list容量+1
  27. size++;
  28. }
  29. /**
  30. * 增加一个集合元素
  31. */
  32. public boolean addAll(Collection<? extends E> c) {
  33. //将c转换为数组
  34. Object[] a = c.toArray();
  35. int numNew = a.length ;
  36. //扩容检查
  37. ensureCapacity( size + numNew); // Increments modCount
  38. //将c添加至list的数据尾部
  39. System. arraycopy(a, 0, elementData, size, numNew);
  40. //更新当前容器大小
  41. size += numNew;
  42. return numNew != 0;
  43. }
  44. /**
  45. * 在指定位置,增加一个集合元素
  46. */
  47. public boolean addAll(int index, Collection<? extends E> c) {
  48. if (index > size || index < 0)
  49. throw new IndexOutOfBoundsException(
  50. "Index: " + index + ", Size: " + size);
  51. Object[] a = c.toArray();
  52. int numNew = a.length ;
  53. ensureCapacity( size + numNew); // Increments modCount
  54. // 计算需要移动的长度(index之后的元素个数)
  55. int numMoved = size - index;
  56. // 数组复制,空出第index到index+numNum的位置,即将数组index后的元素向右移动numNum个位置
  57. if (numMoved > 0)
  58. System. arraycopy(elementData, index, elementData, index + numNew,
  59. numMoved);
  60. // 将要插入的集合元素复制到数组空出的位置中
  61. System. arraycopy(a, 0, elementData, index, numNew);
  62. size += numNew;
  63. return numNew != 0;
  64. }
  65. /**
  66. * 数组容量检查,不够时则进行扩容
  67. */
  68. public void ensureCapacity( int minCapacity) {
  69. modCount++;
  70. // 当前数组的长度
  71. int oldCapacity = elementData .length;
  72. // 最小需要的容量大于当前数组的长度则进行扩容
  73. if (minCapacity > oldCapacity) {
  74. Object oldData[] = elementData;
  75. // 新扩容的数组长度为旧容量的1.5倍+1
  76. int newCapacity = (oldCapacity * 3)/2 + 1;
  77. // 如果新扩容的数组长度还是比最小需要的容量小,则以最小需要的容量为长度进行扩容
  78. if (newCapacity < minCapacity)
  79. newCapacity = minCapacity;
  80. // minCapacity is usually close to size, so this is a win:
  81. // 进行数据拷贝,Arrays.copyOf底层实现是System.arrayCopy()
  82. elementData = Arrays.copyOf( elementData, newCapacity);
  83. }
  84. }
复制代码

5.删除

  1. /**
  2. * 根据索引位置删除元素
  3. */
  4. public E remove( int index) {
  5. // 数组越界检查
  6. RangeCheck(index);
  7. modCount++;
  8. // 取出要删除位置的元素,供返回使用
  9. E oldValue = (E) elementData[index];
  10. // 计算数组要复制的数量
  11. int numMoved = size - index - 1;
  12. // 数组复制,就是将index之后的元素往前移动一个位置
  13. if (numMoved > 0)
  14. System. arraycopy(elementData, index+1, elementData, index,
  15. numMoved);
  16. // 将数组最后一个元素置空(因为删除了一个元素,然后index后面的元素都向前移动了,所以最后一个就没用了),好让gc尽快回收
  17. // 不要忘了size减一
  18. elementData[--size ] = null; // Let gc do its work
  19. return oldValue;
  20. }
  21. /**
  22. * 根据元素内容删除,只删除匹配的第一个
  23. */
  24. public boolean remove(Object o) {
  25. // 对要删除的元素进行null判断
  26. // 对数据元素进行遍历查找,知道找到第一个要删除的元素,删除后进行返回,如果要删除的元素正好是最后一个那就惨了,时间复杂度可达O(n) 。。。
  27. if (o == null) {
  28. for (int index = 0; index < size; index++)
  29. // null值要用==比较
  30. if (elementData [index] == null) {
  31. fastRemove(index);
  32. return true;
  33. }
  34. } else {
  35. for (int index = 0; index < size; index++)
  36. // 非null当然是用equals比较了
  37. if (o.equals(elementData [index])) {
  38. fastRemove(index);
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44. /*
  45. * Private remove method that skips bounds checking and does not
  46. * return the value removed.
  47. */
  48. private void fastRemove(int index) {
  49. modCount++;
  50. // 原理和之前的add一样,还是进行数组复制,将index后的元素向前移动一个位置,不细解释了,
  51. int numMoved = size - index - 1;
  52. if (numMoved > 0)
  53. System. arraycopy(elementData, index+1, elementData, index,
  54. numMoved);
  55. elementData[--size ] = null; // Let gc do its work
  56. }
  57. /**
  58. * 数组越界检查
  59. */
  60. private void RangeCheck(int index) {
  61. if (index >= size )
  62. throw new IndexOutOfBoundsException(
  63. "Index: "+index+", Size: " +size);
  64. }
复制代码

PS:看到了这个方法,便可jdk源码有些地方写的也不是那么精巧,比如这里remove时将数组越界检查封装成了一个单独方法,可是往前翻一下add方法中的数组越界就没有进行封装,需要检查的时候都是写一遍一样的代码,why啊。。。

增加和删除方法到这里就解释完了,代码是很简单,主要需要特别关心的就两个地方:1.数组扩容,2.数组复制,这两个操作都是极费效率的,最惨的情况下(添加到list第一个位置,删除list最后一个元素或删除list第一个索引位置的元素)时间复杂度可达O(n)。

还记得上面那个坑吗(为什么提供一个可以指定容量大小的构造方法 )?看到这里是不是有点明白了呢,简单解释下:如果数组初试容量过小,假设默认的10个大小,而我们使用ArrayList的主要操作时增加元素,不断的增加,一直增加,不停的增加,会出现上面后果?那就是数组容量不断的受挑衅,数组需要不断的进行扩容,扩容的过程就是数组拷贝System.arraycopy的过程,每一次扩容就会开辟一块新的内存空间和数据的复制移动,这样势必对性能造成影响。那么在这种以写为主(写会扩容,删不会缩容)场景下,提前预知性的设置一个大容量,便可减少扩容的次数,提高了性能。

图1.

图2.

上面两张图分别是数组扩容和数组复制的过程,需要注意的是,数组扩容伴随着开辟新建的内存空间以创建新数组然后进行数据复制,而数组复制不需要开辟新内存空间,只需将数据进行复制。

上面讲增加元素可能会进行扩容,而删除元素却不会进行缩容,如果在已删除为主的场景下使用list,一直不停的删除而很少进行增加,那么会出现什么情况?再或者数组进行一次大扩容后,我们后续只使用了几个空间,会出现上面情况?当然是空间浪费啦啦啦,怎么办呢?

  1. /**
  2. * 将底层数组的容量调整为当前实际元素的大小,来释放空间。
  3. */
  4. public void trimToSize() {
  5. modCount++;
  6. // 当前数组的容量
  7. int oldCapacity = elementData .length;
  8. // 如果当前实际元素大小 小于 当前数组的容量,则进行缩容
  9. if (size < oldCapacity) {
  10. elementData = Arrays.copyOf( elementData, size );
  11. }
复制代码

6.更新

  1. /**
  2. * 将指定位置的元素更新为新元素
  3. */
  4. public E set( int index, E element) {
  5. // 数组越界检查
  6. RangeCheck(index);
  7. // 取出要更新位置的元素,供返回使用
  8. E oldValue = (E) elementData[index];
  9. // 将该位置赋值为行的元素
  10. elementData[index] = element;
  11. // 返回旧元素
  12. return oldValue;
  13. }
复制代码

7.查找

  1. /**
  2. * 查找指定位置上的元素
  3. */
  4. public E get( int index) {
  5. RangeCheck(index);
  6. return (E) elementData [index];
  7. }
复制代码

由于ArrayList使用数组实现,更新和查找直接基于下标操作,变得十分简单。

8.是否包含

  1. /**
  2. * Returns <tt>true</tt> if this list contains the specified element.
  3. * More formally, returns <tt>true</tt> if and only if this list contains
  4. * at least one element <tt>e</tt> such that
  5. * <tt>(o==null ? e==null : o.equals(e))</tt>.
  6. *
  7. * @param o element whose presence in this list is to be tested
  8. * @return <tt> true</tt> if this list contains the specified element
  9. */
  10. public boolean contains(Object o) {
  11. return indexOf(o) >= 0;
  12. }
  13. /**
  14. * Returns the index of the first occurrence of the specified element
  15. * in this list, or -1 if this list does not contain the element.
  16. * More formally, returns the lowest index <tt>i</tt> such that
  17. * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  18. * or -1 if there is no such index.
  19. */
  20. public int indexOf(Object o) {
  21. if (o == null) {
  22. for (int i = 0; i < size; i++)
  23. if (elementData [i]==null)
  24. return i;
  25. } else {
  26. for (int i = 0; i < size; i++)
  27. if (o.equals(elementData [i]))
  28. return i;
  29. }
  30. return -1;
  31. }
  32. /**
  33. * Returns the index of the last occurrence of the specified element
  34. * in this list, or -1 if this list does not contain the element.
  35. * More formally, returns the highest index <tt>i</tt> such that
  36. * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  37. * or -1 if there is no such index.
  38. */
  39. public int lastIndexOf(Object o) {
  40. if (o == null) {
  41. for (int i = size-1; i >= 0; i--)
  42. if (elementData [i]==null)
  43. return i;
  44. } else {
  45. for (int i = size-1; i >= 0; i--)
  46. if (o.equals(elementData [i]))
  47. return i;
  48. }
  49. return -1;
  50. }
复制代码

contains主要是检查indexOf,也就是元素在list中出现的索引位置也就是数组下标,再看 indexOf和 lastIndexOf代码是不是很熟悉,没错,和 public boolean remove(Object o) 的代码一样,都是元素null判断,都是循环比较,不多说了。。。但是要知道,最差的情况(要找的元素是最后一个)也是很惨的。。。

9.容量判断

  1. /**
  2. * Returns the number of elements in this list.
  3. *
  4. * @return the number of elements in this list
  5. */
  6. public int size() {
  7. return size ;
  8. }
  9. /**
  10. * Returns <tt>true</tt> if this list contains no elements.
  11. *
  12. * @return <tt> true</tt> if this list contains no elements
  13. */
  14. public boolean isEmpty() {
  15. return size == 0;
  16. }
复制代码

由于使用了size进行计数,发现list大小获取和判断真的好容易。。。

好了,至此ArrayList的分析和注释就基本完成了。什么还差些什么?对, modCount 是干什么的,怎么到处都在操作这个变量,还有遍历呢,为啥不讲?由于iterator遍历相对比较复杂,而且iterator 是GoF经典 设计模式 比较重要的一个,之后会对iterator单独分析,这里就不啰嗦了。。。

ArrayList,完!

来自: http://www.importnew.com/17440.html

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 08:54

Copyright 2015-2025 djqfx

返回顶部