ArrayList原理与底层源码实现

整体架构

成员变量

ArrayList整体架构比较简单,就是一个一维数组。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    
    
    private static final long serialVersionUID = 8683452581122892189L;

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

    /**
     * Shared empty array instance used for empty instances.
     * 空数组
     */
    private static final Object[] EMPTY_ELEMENTDATA = {
    
    };

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     * 默认容量空数组
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {
    
    };

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     * 保存数据的数组
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 数组大小
     * @serial
     */
    private int size;

数据保存在transient Object[] elementData;里面,相当于一个一维数组。
ArrayList继承了AbstractList,protected transient int modCount = 0;统计当前数组被修改的次数。

初始化函数

在这里插入图片描述

  1. ArrayList(int) :指定参数大小初始化

    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);
        }
    }
    

    传入一个参数,为数组初始化容量大小,并初始化数组。int initialCapacity<0则报错。

  2. ArrayList() : 无参直接初始化

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

    不穿参数,则将默认容量的空数组赋值给this.elementData.

  3. ArrayList(Collection<? extends E>):指定初始数据初始化

    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;
        }
    }
    

    该方法传入了一个Collection集合,并对集合类型进行判断,重新复制等。当给定集合内的元素不是 Object 类型时,会转化成 Object 的类型

常用API

新增操作

新增元素有两种方式实现,
新增元素分两步:

  • 判断是否组要扩容,如果需要执行扩容操作。
  • 直接赋值
  1. 末尾追加元素

    /**
     * Appends the specified element to the end of this list.
     * Params: e – element to be appended to this list
     * Returns:true (as specified by Collection.add)
    */
    public boolean add(E e) {
          
          
    	//判断+扩容操作
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
  2. 按索引插入元素

    /**
     * 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!!
        //数组右移
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    

扩容原理

	private void ensureCapacityInternal(int minCapacity) {
    
    
		//初始扩容,确定最小容量
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    
    
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
		//判断容量是否足够
        ensureExplicitCapacity(minCapacity);
    }

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

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
        	//扩容  增加容量
            grow(minCapacity);
    }

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
    
    
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //1.5倍扩容
        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;
    }
  • 扩容后的大小是原来容量的 1.5 倍;
  • ArrayList 中的数组的最大值是 Integer.MAX_VALUE,超过这个值,JVM 就不会给数组分配内存空间了。
  • 新增和扩容没有加锁,线程不安全。

扩容的本质是执行elementData = Arrays.copyOf(elementData, newCapacity);首先是创建一个符合我们预期容量的新数组。然后把老数组的数组拷贝过去。

删除

public E remove(int index) {
    
    
		//索引范围判断
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        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

        return oldValue;
    }

    /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {
    
    
        if (o == null) {
    
    
        	//删除第一个为null的元素
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
    
    
                    fastRemove(index);
                    return true;
                }
        } else {
    
    
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
    
    
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    /*
     * 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
    }

删除操作就是找到要删除的位置,然后数组左移。

浅谈Vector

public synchronized E get(int index) {
    
    
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    /**
     * Replaces the element at the specified position in this Vector with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws ArrayIndexOutOfBoundsException if the index is out of range
     *         ({@code index < 0 || index >= size()})
     * @since 1.2
     */
    public synchronized E set(int index, E element) {
    
    
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

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

    /**
     * Appends the specified element to the end of this Vector.
     *
     * @param e element to be appended to this Vector
     * @return {@code true} (as specified by {@link Collection#add})
     * @since 1.2
     */
    public synchronized boolean add(E e) {
    
    
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }

从源码可以看出来,Vector的核心方法都用synchronized修饰,是线程安全的。
基层实现与ArrayList都是类似的,只是ArrayList不是线程安全。

只有当 ArrayList 作为共享变量时,才会有线程安全问题,当 ArrayList 是方法内的局部变量时,是没有线程安全的问题的。

单线程的情况下,推荐使用ArrayList,因为Vector需要加锁,影响性能。

ArrayList底层实现为数组,适合查找操作。
LinkedList底层为双向链表,增加、删除操作方便。

猜你喜欢

转载自blog.csdn.net/Zhangxg0206/article/details/111192171
今日推荐