Java----ArrayList源码

ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

        ArrayList继承了AbstractList中的get,set,remove,sublist,add等等基础方法。
        实现了list中的sort,addAll,containsAll,toArray等方法。
        实现了RandomAccess,支持快速随机访问。
        实现了Cloneable,可以被克隆。
        实现了Serializable,可以序列化。
 transient Object[] elementData;
 底层使用数组实现

构造方法

指定一个初始容量的空列表
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);
        }
    }

   指定一个空列表
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    可以将一个继承了Collection的类转换为ArrayList
    public ArrayList(Collection<? extends E> c) {
       // 转换为数组
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
          // 替换为一个空数组
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

元素存储

add相关方法

    //返回数组中的值
    E elementData(int index) {
        return (E) elementData[index];
    }
   //检查index是否超过范围
   private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    //根据index获取元素
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

  //设置元素,用指定的元素替换index位置上的元素
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
     //判断是否进行扩容
     private void ensureCapacityInternal(int minCapacity) {
         //首先判断现在的ArrayList是不是空的,如果是空的,minCapacity就取默认的容量和传入的参数minCapacity中的大值
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        //如果minCapacity的值大于add数据之前的大小,就调用grow方法,进行扩容,否则什么也不做
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

   private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    //新的容量 = 老容量+老容量/2,扩容为原有大小的1.5倍
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    //新容量<老容量
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    //新容量不能大于最大值,MAX_ARRAY_SIZE 为
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    //容量不能大于最大值
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) 
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    //手动进行扩容的方法
    public void ensureCapacity(int minCapacity) {
            //不为空,容量为0,否则为10
            int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0: DEFAULT_CAPACITY;
            if (minCapacity > minExpand) {
                ensureExplicitCapacity(minCapacity);
            }
    }
    //添加元素的方法
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    //添加元素到指定位置
    public void add(int index, E element) {
    //检查是否超出范围
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  
        //将elementData从index开始后面的元素往后移一位。       
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    //删除arrayLisy指定位置的元素
    public E remove(int index) {
        rangeCheck(index);

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

        int numMoved = size - index - 1;
        if (numMoved > 0)
            //将index后面所有的元素往前移一位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null;

        return oldValue;
    }
     private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
        //将elementData从index开始后面的元素往前移
        System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //不断把最后一个元素置为空
        elementData[--size] = null; 
    }
    //移除容器中值为o的元素
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
            //如果值相等,移除值相等的那个元素,index往后的元素向前移一位
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
    //清除容器
    public void clear() {
        modCount++;

        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
    // 按照指定collection的迭代器所返回的元素顺序,将该collection中的所有元素添加到此列表的尾部。  
    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;
    }
    // 从指定的位置开始,将指定collection中的所有元素插入到此列表中。 
    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;
    }
   //返回数组中第index个
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
   //设置容器中第index个元素的值
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
     //容器中元素的下标
      public int indexOf(Object o) {
            if (o == null) {
                for (int i = 0; i < size; i++)
                    if (elementData[i]==null)
                        return i;
            } else {
                for (int i = 0; i < size; i++)
                    if (o.equals(elementData[i]))
                        return i;
            }
            return -1;
        }
    //返回元素最后出现位置的下标
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
  //去除容器中多余位置,比如我们需要11个元素,add时扩容为15个,实际我们只需要11个
  public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
    //是否包含元素
   public boolean contains(Object o) {
       return indexOf(o) >= 0;
   }
    //排序
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值