Java集合系列源码分析(一)--ArrayList

一、ArrayList

ArrayList是非常常用的集合类之一,其对数组进行封装,并进行动态的增加和缩减长度。因为底层是数组,所以写的效率要低点,因为涉及到新内存的开辟和数组元素的拷贝,但是查询效率非常高。非线程安全

二、源码分析

2.1 继承结构和层次
在这里插入图片描述
在这里插入图片描述
可以看到Arraylist继承抽象类AbstractList,而AbstractList继承自AbstractCollection

其中:
RandomAccess:标记接口,表明ArrayList支持快随随机访问。实现此接口则使用for循环来遍历,性能更高
List:父接口
Cloneable:可以使用克隆
Serializable:实现了序列化接口,表明可以被序列化

2.2 ArrayList属性

	//版本号
   private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默认初始化容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 自定义容量为0,则使用此来初始化ArrayList
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 如果没有自定义容量,则会使用此来初始化ArrayList
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 元素数组,不允许序列化,无private修饰
     */
    transient Object[] elementData; 

    /**
     * 集合大小(包含元素数量)
     */
    private int size;
    
    /**
     * 最大容量
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

2.3 构造方法

构造方法有三种:
在这里插入图片描述
2.3.1 无参构造方法

默认大小为10,将空的Object[]数组给elementData初始化

public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

2.3.2 带参构造方法1

根据传入参数初始化数组大小,判断传入参数正确性,小于0抛出参数错误

为0则用EMPTY_ELEMENTDATA的空数组初始化elementData

  /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

2.3.3 带参构造方法2

传入一个集合类(Collection的子类),转化为list

/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 *
 * @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();
    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;
    }
}

2.4 集合操作

2.4.1 添加

在这里插入图片描述

  1. boolean add(E e)

在末尾位置添加元素。首先校检数组空间是否足够,如果不够则进行扩容。扩容之后在数组位置放入新元素

以空list添加第一个元素为例分析源码

   /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //elementData[size] = e, size++
        elementData[size++] = e;
        return true;
    }

首先看ensureCapacityInternal(size+1)方法,其中又嵌套了两个方法

private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

//1.首先调用此方法来计算容量:如果elementData为空,返回默认10和minCapacity即size+1=1(此时size为0)的最大值,即返回10,否则返回size+1。此时底层数组容量仍然为0
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

//2.确保容量可用,modCount用来计算修改次数  

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
    	//如果minCapacity即10>elementData.length,即底层数组长度小于minCapacity(10),则调用grow进行扩容
        grow(minCapacity);
}

//3.扩容(minCapacity=10)
private void grow(int minCapacity) {
    // overflow-conscious code
    //获取旧数组长度,此时为0
    int oldCapacity = elementData.length;
    //新数组长度=旧长度+旧长度/2=1.5倍旧长度,此时为0
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
    //0 - 10 = -10 < 0,符合条件,则设置newCapacity = 10
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
    //如果newCapacity大于最大容量限制,调用hugeCapacity方法
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    //长度确认,进行copy操作,初始化elementData大小为10
    elementData = Arrays.copyOf(elementData, newCapacity);
}

//最大返回Integer的最大值
 private static int hugeCapacity(int minCapacity) {
     if (minCapacity < 0) // overflow
         throw new OutOfMemoryError();
     return (minCapacity > MAX_ARRAY_SIZE) ?
         Integer.MAX_VALUE :
         MAX_ARRAY_SIZE;
 }
  1. void add(int index, E element)

指定位置添加,无返回值

   /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
    	//检测位置索引是否正确,错误抛出异常
        rangeCheckForAdd(index);

		//确认空间,是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //将index位置后的元素后移
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //新元素添加至elementData的index位置
        elementData[index] = element;
        //长度增加
        size++;
    }

    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
  1. boolean addAll(Collection<? extends E> c)

添加全部集合,不多说了

public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}
  1. boolean addAll(int index, Collection<? extends E> c

指定位置添加全部集合,不多说了

public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index);

    Object[] a = c.toArray();
    int numNew = a.length;

    ensureCapacityInternal(size + numNew);  // Increments modCount

    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew,
                         numMoved);

    System.arraycopy(a, 0, elementData, index, numNew);
    size += numNew;
    return numNew != 0;
}

简单总结下add操作:

  1. 一般使用 List<> list = new ArrayList<>(); 创建Arraylist时,此时底层的数组Object[] elementData为空,长度为0。
    添加第一个元素时,才对elementData进行了扩容,将elementData的大小变为10,再对list添加元素
  2. 当使用带参初始化有长度的elementData数组时,再添加的第一个元素则不会引起扩容机制,直接添加进入数组,可参照上述源码分析
  3. 每次扩容大小为旧数组长度的1.5倍
  4. 按位置插入需检查位置索引并将数组移动,其他部分的机制同直接添加

2.4.2 删除
在这里插入图片描述

  1. E remove(int index)
   public E remove(int index) {
   		//校检index
        rangeCheck(index);
		
        modCount++;
        //获取该索引位置元素
        E oldValue = elementData(index);
		
		//计算要移动的位数
        int numMoved = size - index - 1;
        if (numMoved > 0)
        	//移动元素
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //将移动后多出的元素位置复制为null
        elementData[--size] = null; // clear to let GC do its work
		
		//返回删除的元素
        return oldValue;
    }
  1. boolean remove(Object o)

先介绍下fastRemove,有点类似与上面的删除,可以删除index位置元素

/*
 * Private remove method that skips bounds checking and does not
 * return the value removed.
 */
private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}

fastRemove在remove(Object o)中会用到

  public boolean remove(Object o) {
  		//如果o==null,则遍历查找为null的元素,找到后删除
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
        	//不为null,则遍历查找元素o,找到后删除
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

可以看出Arraylist可以添加null值

  1. boolean removeAll(Collection<?> c)

移除所有

public boolean removeAll(Collection<?> c) {
	//检查c不为null
    Objects.requireNonNull(c);
    //批量删除
    return batchRemove(c, false);
}

batchRemove方法

   private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
            	//检查集合c是否包含elementData中的元素
                if (c.contains(elementData[r]) == complement)
                	//不包含,保留
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

其他的就不说了

remove简单总结下:

  • 删除对应位置元素,后面位置元素前移,最后多出的一个元素置为null,clear to let GC do its work

2.4.3 修改

传入的index校检,修改index位置数据,返回旧数据,比较简单

public E set(int index, E element) {
    rangeCheck(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

2.4.4 查询

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
查询方法比较简单,源码都很容易,不多做解析

public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

三、总结

  1. ArrayList底层是一个长度可变的数组
  2. 遍历和随机查询速度很快,但是插入删除比较慢,需要移动较多的数据
  3. 遍历时使用for循环速度较快,遍历时删除需注意删除操作,否则会报错(如越界或ConcurrentModificationException)
  4. 可以存放null值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值