ArrayList用法及源码解析

本文详细介绍了ArrayList的基本概念、内部结构、与LinkedList的区别以及常用方法,并提供了示例代码。

转载请注明出处:http://blog.youkuaiyun.com/github_39430101/article/details/76166174

ArrayList简介

ArrayList实现了List接口,内部以数组存储数据,允许重复的值。由于内部是数组实现,所以ArrayList具有数组所有的特性,通过索引支持随机访问,查询速度快,但是插入和删除的效率比较低。ArrayList是非线程安全的,所以建议在单线程中使用ArrayList,在多线程中选择Vector或者CopyOnWriteArrayList。

ArrayList结构

这里写图片描述

和LinkedList主要区别

1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。
2.对于随机访问get和set,ArrayList优于LinkedList,因为LinkedList要移动指针。
3.对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。

常用方法

返回类型方法用法
booleanadd(E e)将指定的元素添加到此列表的尾部
voidadd(int index, E element)将指定的元素插入此列表中的指定位置
voidclear()移除此列表中的所有元素
Objectclone()返回此 ArrayList 实例的浅表副本
booleancontains(Object o)如果此列表中包含指定的元素,则返回 true
Eget(int index)返回此列表中指定位置上的元素
intindexOf(Object o)返回此列表中首次出现的指定元素的索引,或如果此列表不包含元素,则返回 -1
intlastIndexOf(Object o)返回此列表中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回 -1
booleanisEmpty()如果此列表中没有元素,则返回 true
Eremove(int index)移除此列表中指定位置上的元素
booleanremove(Object o)删除ArrayList中指定的元素
protected voidremoveRange(int fromIndex, int toIndex)移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素
Eset(int index, E element)用指定的元素替代此列表中指定位置上的元素
intsize()返回此列表中的元素数
Object[]toArray()按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组
voidtrimToSize()将此 ArrayList 实例的容量调整为列表的当前大小

Demo

package com.code.array;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayTest {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        // add方法
        list.add("张三");
        list.add("李四");
        list.add("王麻子");
        list.add("赵云");
        list.add("关羽");
        list.add("曹操");

//      第一种遍历方法
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));   
        }
//      第二种遍历方法 foreach循环
        for(String v :list) {
            System.out.println(v);
        }

//      第三种遍历方法
        Iterator<String> i = list.iterator();
        while(i.hasNext()) {
            System.out.println(i.next());
        } 

        list.add(0, "张飞");


        if(list.contains("赵云")) {
            System.out.println("我乃常山赵子龙");
        } else System.out.println("没有赵云");


        System.out.println(list.indexOf("赵云"));
        //lastIndexOf(Object o)

        System.out.println(list.lastIndexOf("张三"));

        System.out.println(list.isEmpty());
        //循环删除
        for (int x =list.size()-1;x>=0;x--) {
            list.remove(list.get(x));
        }
    }
}

ArrayList源码


package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    //序列版本号
    private static final long serialVersionUID = 8683452581122892189L;
    // 默认初始数组大小
    private static final int DEFAULT_CAPACITY = 10;
    //空数组,用来实例化不带容量大小的构造函数
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //用于默认大小的空实例的共享空数组实例。
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    //保存ArrayList数组数据
    transient Object[] elementData; 
    //数组包含元素的个数
    private int size;

    /********** 三个构造函数 *********/

    //带参构造函数
    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的构造方法
    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;
        }
    }
    /*************** ArrayList扩容原理 ************/
    //修改当前容量为实际个数
    public void trimToSize() {
        modCount++;
        //如果当前个数小于数组的容量,则把数组大小设置为当前的size
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    //将此 ArrayList 实例的容量调整为列表的当前大小,是提供给外界的方法,真正的扩容是在下面的private方法里
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            ? 0
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
   ensureExplicitCapacity(minCapacity);
    }

    //ArrayList扩容
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        //如果新的数组大小大于之前数组大小,则调用扩容方法
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    //分配的最大数组空间
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    //扩容
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新的容量=原来的容量+原来的容量/2
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        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;
    }
    /********* 常用方法 **************/
    //返回当前数组大小
    public int size() {
        return size;
    }
    //判断数组是否为空
    public boolean isEmpty() {
        return size == 0;
    }
    //判断数组是否包含某个元素
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    //返回此列表中首次出现的指定元素的索引
    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;
    }

    //克隆
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    //返回一个Object数组,包含ArrayList中所有的元素
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    //返回ArrayList的模板数组
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    //返回此列表中指定位置上的元素
    public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }

    //用指定的元素替代此列表中指定位置上的元素
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
    //将指定的元素添加到此列表的尾部
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    // 将指定的元素插入此列表中的指定位置
    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++;
    }

     //移除此列表中指定位置上的元素
    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;
    }

    //删除ArrayList中指定的元素
    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++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

       //快速删除,跳过边界检查且没有返回值
    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
    }

      //移除此列表中所有元素
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    //将集合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;

    //从指定的位置开始,将指定 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;
    }

    //除从fromIndex到toIndex之间的数据,不包括toIndex位置的数据
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    //范围检查
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

      //由add和addAll使用的rangeCheck的一个版本
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    //删除ArrayList中所有集合C中包含的数据
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    //删除ArrayList中除了集合C中包含的数据外的其他所有数据
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
    //批量删除
    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++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
      //保留与AbstractCollection的行为兼容性
            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;
    }
/************ ArrayList与IO *********/

//将ArrayList的容量和元素都写入到输出流中
private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        int expectedModCount = modCount;
        s.defaultWriteObject();
        s.writeInt(size);
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    //先将ArrayList的“容量”读出,然后将“所有的元素值”读出 
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;
        s.defaultReadObject();

        s.readInt(); 

        if (size > 0) {
            ensureCapacityInternal(size);

            Object[] a = elementData;

            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

注意: ArrayList循环遍历并删除元素的常见错误

错误一、
public static void main(String[] args){
    List<String> list = new ArrayList<String>();
    list.add("刘备");
    list.add("关羽");
    list.add("张飞");
    for (String s:list){
        list.remove(s);
    }
}

这里写图片描述
错误原因:foreach写法是对迭代器的简写,我们的remove方法修改了modCount的值

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

父类AbstractList checkForComodification方法

final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

这里会做迭代器内部修改次数检查,如果检查到不相等则抛出异常。要避免这种情况的出现则在使用迭代器迭代时(显示或for-each的隐式)不要使用ArrayList的remove,改为用Iterator的remove即可。

错误二、
public static void main(String[] args){
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    for(int i=0;i<list.size();i++){
        System.out.println(list.get(i));
    }
}

这里写图片描述
错误原因:每删除一个元素时,它后面的一个元素会向前移一位

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

这种情况可以用倒序删除来解决。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值