java ArrayList源码学习,分析

今天药忘吃喽~ 2022-03-30 15:52 326阅读 0赞
ArrayList 简介

ArrayList是一个动态数组,它能够自动进行扩容。
继承自AbstractList,implements 实现了 List, RandomAccess (随机访问–空接口), Cloneable(克隆–空接口), java.io.Serializable(序列化)
与vector相比,不是线程安全的容器,但效率相对高些,所以在单线程中推荐使用ArrayList,多线程中可以使用Vector

ArrayList :以下均是基于JDK1.8

  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  3. {
  4. private static final long serialVersionUID = 8683452581122892189L; //序列化UUID
  5. private static final int DEFAULT_CAPACITY = 10; //初始化默认容量
  6. private static final Object[] EMPTY_ELEMENTDATA = {}; //静态 final 空数组,设置容器大小为0时,直接等于这个值
  7. transient Object[] elementData; // 存储数据的Object数组
  8. private int size; //记录实际存储数据的个数
  9. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //array最大个数
构造器
参数为设置初始化容器的构造函数
  1. public ArrayList(int initialCapacity) {
  2. if (initialCapacity > 0) {
  3. this.elementData = new Object[initialCapacity];
  4. } else if (initialCapacity == 0) { //如果容量为0,设置 直接设置为EMPTY_ELEMENTDATA
  5. this.elementData = EMPTY_ELEMENTDATA;
  6. } else { //否则抛出异常
  7. throw new IllegalArgumentException("Illegal Capacity: "+
  8. initialCapacity);
  9. }
  10. }
默认构造器:
  • 容器容量默认为10

    /**

    1. * Constructs an empty list with an initial capacity of ten.
    2. */
    3. public ArrayList() {
    4. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    5. }
集合形式构造器
  1. public ArrayList(Collection<? extends E> c) {
  2. elementData = c.toArray();
  3. if ((size = elementData.length) != 0) {
  4. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  5. if (elementData.getClass() != Object[].class)
  6. elementData = Arrays.copyOf(elementData, size, Object[].class);
  7. } else {
  8. // replace with empty array.
  9. this.elementData = EMPTY_ELEMENTDATA;
  10. }
  11. }
内置方法

trimTosize():应该是去除多余的空间,如果存储的个数少于数组的长度,说明有多余的剩余空间,调用Arrays.copyOf()方法

  1. /**
  2. * Trims the capacity of this <tt>ArrayList</tt> instance to be the
  3. * list's current size. An application can use this operation to minimize
  4. * the storage of an <tt>ArrayList</tt> instance.
  5. */
  6. public void trimToSize() {
  7. modCount++;
  8. if (size < elementData.length) {
  9. elementData = (size == 0)
  10. ? EMPTY_ELEMENTDATA
  11. : Arrays.copyOf(elementData, size);
  12. }
  13. }
ArrayList扩容机制

确定ArrayList的容量 : 如果当前容量不足以容纳当前的元素的个数,调用ensureExplicitCapacity()方法

  1. public void ensureCapacity(int minCapacity) {
  2. int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
  3. // any size if not default element table
  4. ? 0
  5. // larger than default for default empty table. It's already
  6. // supposed to be at default size.
  7. : DEFAULT_CAPACITY;
  8. if (minCapacity > minExpand) {
  9. ensureExplicitCapacity(minCapacity);
  10. }
  11. }

如果容量不足,需要调用grow()

  1. private void ensureExplicitCapacity(int minCapacity) {
  2. modCount++;
  3. // overflow-conscious code
  4. if (minCapacity - elementData.length > 0)
  5. grow(minCapacity);
  6. }

调用grow(),真正进行扩容的地方,扩容为1.5倍

  1. /**
  2. * Increases the capacity to ensure that it can hold at least the
  3. * number of elements specified by the minimum capacity argument.
  4. *
  5. * @param minCapacity the desired minimum capacity
  6. */
  7. private void grow(int minCapacity) {
  8. // overflow-conscious code
  9. int oldCapacity = elementData.length; //oldCapacity为当前容器的长度
  10. int newCapacity = oldCapacity + (oldCapacity >> 1); //新长度为原来长度右移一位,也就是/2,一半,在加上原来的长度
  11. if (newCapacity - minCapacity < 0) //新长度比原来小
  12. newCapacity = minCapacity;
  13. if (newCapacity - MAX_ARRAY_SIZE > 0)//新长度比最大size大(也就是Integer的最大值-8)
  14. newCapacity = hugeCapacity(minCapacity);
  15. // minCapacity is usually close to size, so this is a win:
  16. // 拷贝原数组中的元素至新数组,并返回新数组的引用
  17. elementData = Arrays.copyOf(elementData, newCapacity); //正常情况下,1.5倍
  18. }
ArrayList常用方法、

在这里插入图片描述

ArrayList的内部类–迭代器

迭代器原理:
迭代器是对集合进行遍历, 而每一个集合内部的存储结构都是不同的,所以每一个集合存和取都是不一样, 那么就需要在每一个类中定义hasNext()和next()方法,这样做是可以的,但是会让整个集合体系过于臃肿, 迭代器是将这样的方法向上抽取出接口,然后在每个类的内部,定义自己迭代方式,

  • 好处

    • 第一规定了整个集合体系的遍历方式都是hasNext()和next()方法,
    • 第二,代码有底层内部实现,使用者不用管怎么实现的,会用即可

    private class ListItr extends Itr implements ListIterator {

    1. ListItr(int index) {
    2. super();
    3. cursor = index;
    4. }
    5. public boolean hasPrevious() {
    6. return cursor != 0;
    7. }
    8. public int nextIndex() {
    9. return cursor;
    10. }
    11. public int previousIndex() {
    12. return cursor - 1;
    13. }
    14. @SuppressWarnings("unchecked")
    15. public E previous() {
    16. checkForComodification();
    17. int i = cursor - 1;
    18. if (i < 0)
    19. throw new NoSuchElementException();
    20. Object[] elementData = ArrayList.this.elementData;
    21. if (i >= elementData.length)
    22. throw new ConcurrentModificationException();
    23. cursor = i;
    24. return (E) elementData[lastRet = i];
    25. }
    26. public void set(E e) {
    27. if (lastRet < 0)
    28. throw new IllegalStateException();
    29. checkForComodification();
    30. try {
    31. ArrayList.this.set(lastRet, e);
    32. } catch (IndexOutOfBoundsException ex) {
    33. throw new ConcurrentModificationException();
    34. }
    35. }
    36. public void add(E e) {
    37. checkForComodification();
    38. try {
    39. int i = cursor;
    40. ArrayList.this.add(i, e);
    41. cursor = i + 1;
    42. lastRet = -1;
    43. expectedModCount = modCount;
    44. } catch (IndexOutOfBoundsException ex) {
    45. throw new ConcurrentModificationException();
    46. }
    47. }
    48. }
ArrayList的遍历方式
  1. 1. 迭代器
  2. 2. 随机访问,通过索引
  3. 3. for循环遍历

ArrayList的遍历代码就不写了,也都很简单…偷个懒…

发表评论

表情:
评论列表 (有 0 条评论,326人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ArrayList分析

    构造函数(有参和无参): 无参:有个被transient关键字修饰的elementData的Object类型长度为0的数组。 有参:参数的含义就是这个集合的含量,在Arra