List的实现类之间的区别以及ArrayList的源码解析

1.List的实现类有ArrayList, LinkedList, Vactor, Stack;

ArrayList:底层是动态数组结构,数据查询方便、数据增删改不方便,线程不安全,本质上就是通过定义新的更大的数组,将旧数组内容拷贝到新数组,来实现扩容。当我们调用无参构造的方法来构造Arraylist的对象时,它会在内部分配一个初始大小为10的 Object类型的数组。当添加的数据容量超过数组的大小时,会产生一个新的数组,新的数组大小为原数组的1.5倍,接着把原数组中的数据复制到新数组中。

LinkedList:底层是双向链表结构,数据增删改方便,数据查询不方便,线程不安全;它内部封装的是双向链表的数据结构,每个节点是一个Node对象, Node对象中封装的是你要添加的元素,还有一个指向上一个Node对象的引用和一个指向下一个Node对象的引用。

Vactor:底层是动态数组结构,线程安全,和ArrayList类似,但属于强同步类。如果你的程序本身是线程安全的(thread-safe,没有在多个线程之间共享同一个集合/对象),那么使用ArayList是更好的选择。当添加的数据容量超过数组的大小时,会产生一个新的数组,新的数组大小为原数组的2倍;有句话叫越安全,效率就越低。Stack:底层是动态数组结构,线程安全,Stack继承自Vector,实现一个后进先出的堆栈。

Stack提供5个额外的方法使得Vector得以被当作堆栈使用。基本的push和pop方法,还有peek方法得到栈顶的元素, empty方法测试堆栈是否为空, search方法检测一个元素在堆栈中的位置。Stack刚创建后是空栈。

2如何选用ArrayList, LinkedList, Vector?

线程安全时,用Vector.

局部变量不存在线程安全问题时,并且查找较多用ArrayList (一般使用它)

局部变量不存在线程安全问题时,增加或删除元素较多用LinkedList.

本来想把这几个源码都放一起的但是放一起太多剩下下一个文章里

ArrayList源码解析

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    //序列化ID
    private static final long serialVersionUID = 8683452581122892189L;
    //容器默认初始化大小
    private static final int DEFAULT_CAPACITY = 10;
    //一个空对象
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //一个空对象,如果使用默认构造函数创建ArrayList,则默认对象内容是该值
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    //ArrayList存放对象的容器,后面的添加、删除等操作都是基于该属性来进行操作
    transient Object[] elementData;
    //当前列表已使用的长度
    private int size;
    //数组最大长度(2147483639),这里为什么是Integer.MAX_VALUE - 8是因为有些虚拟机在数组中保留了一些头部信息,防止内存溢出
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    //这个是从AbstractList继承过来的,代表ArrayList集合修改的次数
    protected transient int modCount = 0;

    //创建一个定义好长度的集合
    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;
    }

    //这个构造方法构造了一个包含指定元素的集合,注意,这里的字符E是一个标记,用来表示集合中元素的类型。至于具体是什么类型,需要你在使用这个构造方法的时候来指定
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();//将参数中的集合放入数组容器中
        if ((size = elementData.length) != 0) {//将容器中的集合长度赋给size并且值不能是0
            if (elementData.getClass() != Object[].class)//Arrays中有一个 "类似" ArrayList 的List ,这个List 的toArray 返回的是一个泛型数组,那么,不等条件就成立了
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {//如果长度是0创建一个空的集合
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    //将elementData的数组设置为ArrayList实际的容量
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);//用Arrays.copyOf(T [],int newLength)这个方法来截取elementData数组。
        }
    }

    //可以对ArrayList低层的数组进行扩容
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 
        0: DEFAULT_CAPACITY;//如果数组是空的minExpand=0如果不是使用默认值10
        if (minCapacity > minExpand) {//如果传入的参数比minExpand大进行扩容
            ensureExplicitCapacity(minCapacity);
        }
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//如果elementData是空的
            return Math.max(DEFAULT_CAPACITY, minCapacity);//比较返回大的数
        }
        return minCapacity;//否者返回minCapacity
    }

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

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        if (minCapacity - elementData.length > 0)//判断是否需要扩容
            grow(minCapacity);//进行扩容
    }

    //扩容
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;//原来集合的长度
        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;
    }

    //当前列表已使用的长度
    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) {
            throw new InternalError(e);
        }
    }

    //按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组(转成Object[])
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    //按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。(转成指定类型的数组)
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

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

    //删除元素(指定对象)
    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;
    }

    //将index后边的对象往前复制一位,并将数组中的最后一位元素设置为null,释放对象的引用
    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
    }

    //清除集合(将所有元素设置为null)
    public void clear() {
        modCount++;
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

    //新增集合(集合的最后面)
    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;
    }

    //新增集合(指定位置)
    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;
    }
    
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    //判断下标是否正确
    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;
    }

    //删除元素(指定对象集合)
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    //保留元素(删除其他元素)
    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 {
            if (r != size) {
                System.arraycopy(elementData, r, elementData, w,size - r);
                w += size - r;
            }
            if (w != size) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

    //从指定位置开始迭代
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    //迭代所有元素
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    //迭代所有元素
    public Iterator<E> iterator() {
        return new Itr();
    }

    //截取指定范围的元素(arrayList没有subList方法而是继承了AbstractList类里的)
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    //从源码中可以看出spiterator返回一个Spliterator对象。
    //Spliterator用于遍历和分隔一个对象中的元素,这个对象必须实现Spliterator接口,实现这个接口类有Collection,数组等。
    //Spliterator可以逐个的遍历元素,或者批量的遍历。
    //Spliterator是一个可以分割的迭代器,可以将Spilterator实例分割成多个小的Spilterator实例
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    //按照一定规则过滤集合中的元素
    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    //将元素替换成返回的结果
    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    //集合按照指定规则排序
    @Override
    @SuppressWarnings("unchecked")
    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++;
    }
}

猜你喜欢

转载自www.cnblogs.com/liyijie/p/12156869.html
今日推荐