java collection 集合之list

collection中几种常用的集合类型特点

| 集合类型 | 是否允许空 | 是否允许重复数据 | 是否有序 | 是否线程安全
| ------------- |-------------| -----| -----|
| ArrayList | 是| 是 | 是 | 否
| Vector | 是| 是 | 是 | 是(相对线程安全)
| LinkedList | 是| 是 | 是 | 否
|CopyOnWriteArrayList | 是| 是 | 是 | 是(绝对的线程安全)

所有代码均是jdk1.8版本下
底层实现

ArrayList

	private transient Object[] elementData;
	是由一个transient修饰的object数组实现
	ps:transient是不希望elementData被序列化,因为arrayList初始化之后是有固定的长度的,如默认的10,但elementData里面可能只有3个元素,没必要序列化整个elementData

Vector

   与ArrayList类似,vector底层也是由Object[] 数组实现
   protected Object[] elementData;
   不同的是 vector是没有transient来修饰的。意味了在序列化的时候会将数组中为空的元素也序列化

LinkedList

	LinkedList的各项特质与ArrayList一致,但是底层实现上是完全不一样的。
	LinkedList是基于链表实现,是一种双向链表,链表是一种线性的存储结构,链表中的每个元素都由三部分组成。 
	Node<E> prev, E element, Node<E> next
	prev和next分别指向前一个存储单元和后一个存储单元的引用地址
	

CopyOnWriteArrayList

	顾名思义,这个类就是arraylist的并发版本,位于juc包下。根据CopyOnWrite可以看出这个类是读写分离的。任何可变的操作都是伴随着复制。
	底层也是由
	private transient volatile Object[] array;
	轻量级volatile修饰的一个Object数组
	

初始化

ArrayList

	 /**如不指定初始化集合大小,默认是10,这个10不是new ArrayList<>()初始化的时候赋值的,是在第一次调用的时候赋值*/
	List<Object> list = new ArrayList<>(); 
	/**初始化一个大小为16的数组*/
	List<Object> list1 = new ArrayList<>(16);

Vector

	 /**不指定容量的大小, 会调new Vector<>(10) 方法创建一个大小为10的数组*/
      Vector<Object> vector = new Vector<>();
      /**指定容量大小*/
      Vector<Object> vector1 = new Vector<>(16);
      /**指定容量大小和增长因子*/
      Vector<Object> vector2 = new Vector<>(16, 2);

      List<Object> list = new ArrayList<>();
      /**将Collection的集合初始化到Vector中,大小是list的长度*/
      Vector<Object> vector3 = new Vector<>(list);

LinkedList

	/**linkedlist的初始化没有任何容量跟增长因子*/
	List<Object> list = new LinkedList<>();

    List<Object> tempList= new ArrayList<>();
    /**将Collection的集合初始化到LinkedList中,大小是list的长度*/
    List<Object> list1 = new LinkedList<>(tempList);
	/**LinkedList的内部类*/
	private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

CopyOnWriteArrayList

	private transient volatile Object[] array;
    /**getter/setter方法*/
    final Object[] getArray() {
        return array;
    }
    final void setArray(Object[] a) {
        array = a;
    }
    /**创建一个空数组*/
    public CopyOnWriteArrayList() {
        setArray(new Object[0]);
    }
    与array list的区别是并没有初始大小的数组,而是空数组

添加

ArrayList

    transient Object[] elementData;
    //默认容量大小
    private static final int DEFAULT_CAPACITY = 10;
    //默认空数组
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    //数组的长度
    private int size;
	//最大的数组长度
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 在数组队尾添加一个元素
     */
    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++;
    }

	/**确保当前数组的长度可用*/
    private void ensureCapacityInternal(int minCapacity) {
        //如果当前数组为空,则获取 默认容量 跟 参数容量中大的一个
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        //当前容器修改的次数
        modCount++;
        /**如果不可用了,增加容量*/
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        /**  
         * 看到好多文档,博客上直接写明扩容的长度就是原来的1.5倍,
         * 个人理解,oldCapacity的值可能是 0,10,15,22, 33, 48, 62 并不是严格意义上的1.5倍
         * 初始后的第一次扩容,oldCapacity = 10 ,二进制是 1010 右移 0101是5,新容量是15
         * 第二次扩容 oldCapacity 15 二进制是1111 右移 1 得 0111 是 7 新容量是22 
         */
        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);
    }

	新增的最后都调用了Arrays.copyOf System.arrayCopy 等函数,创建一个新的数组,将原来的数组赋值到新数组上

Vector

	与ArrayList实现方式类似,不同的方法签名上是有Synchronized来修饰的。
	//扩容的方式
	private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        /**如果指定了增长因子,则每次扩容加上增长因子,如果没有,则翻倍*/
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

LinkedList

public boolean add(E e) {
        linkLast(e);
        return true;
    }

    void linkLast(E e) {
	    //获取当前链表中最后一个元素
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

CopyOnWriteArrayList

	final transient ReentrantLock lock = new ReentrantLock();
	public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            /**核心动作,复制一个新数组*/
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    public void add(int index, E element) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            if (index > len || index < 0)
                throw new IndexOutOfBoundsException("Index: "+index+
                                                    ", Size: "+len);
            Object[] newElements;
            int numMoved = len - index;
            if (numMoved == 0)
                newElements = Arrays.copyOf(elements, len + 1);
            else {
                newElements = new Object[len + 1];
                System.arraycopy(elements, 0, newElements, 0, index);
                System.arraycopy(elements, index, newElements, index + 1,
                                 numMoved);
            }
            newElements[index] = element;
            setArray(newElements);
        } finally {
            lock.unlock();
        }
    }
    对当前操作的方法加上重入锁,每次有更新动作都会复制一个新数组,并将原数组的引用转移到新数组上。

删除

ArrayList

	/**
		移除指定下标的元素
	*/
    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;
    }
	在指定位置插入元素的时间复杂度是o(size - index)

    /**
     * 移除第一个等于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++)
                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

	与ArrayList实现方式类似,不同的方法签名上是有Synchronized来修饰的。

LinkedList

public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
    移除操作跟新增操作都是操作node的prev跟next将它们的引用指向新的元素
    为了找到插入,删除的元素,linkedlist的操作方式是分别从首尾两端向index处进行遍历,时间复杂度是o(index)

CopyOnWriteArrayList

public E remove(int index) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            E oldValue = get(elements, index);
            int numMoved = len - index - 1;
            if (numMoved == 0)
                setArray(Arrays.copyOf(elements, len - 1));
            else {
                Object[] newElements = new Object[len - 1];
                System.arraycopy(elements, 0, newElements, 0, index);
                System.arraycopy(elements, index + 1, newElements, index,
                                 numMoved);
                setArray(newElements);
            }
            return oldValue;
        } finally {
            lock.unlock();
        }
    }

总结

ArrayList
从ArrayList的源码不难看出它的核心方法是扩容和数组复制
优点如下:

  1. 底层是数组实现,是一种随机访问模式,实现了RandomAccess接口,查找速度快
  2. 顺序添加元素的时候快,
    缺点:
    插入和删除时涉及到数组的复制拷贝,如果数组的元素较多,会影响性能。

LinkedList
1.插入效率
顺序插入时ArrayList会比较快,因为linkedlist每次新增一个对象出来,如果对象比较大,那么new的时间势必会长一点,再加上一些引用赋值的操作,所以顺序插入LinkedList必然慢于ArrayList。
ArrayLIst随机插入的时间复杂度是o(size - index)
LinkedList随机插入的时间复杂度是o(index) index 最大不会超过size的一半
如果待插入、删除的元素是在数据结构的前半段尤其是非常靠前的位置的时候,LinkedList的效率将大大快过ArrayList,因为ArrayList将批量copy大量的元素;越往后,对于LinkedList来说,因为它是双向链表,所以在第2个元素后面插入一个数据和在倒数第2个元素后面插入一个元素在效率上基本没有差别,但是ArrayList由于要批量copy的元素越来越少,操作速度必然追上乃至超过LinkedList
2.内存会比ArrayList耗费更多一点
3.使用各自遍历效率最高的方式,ArrayList的遍历效率会比LinkedList的遍历效率高一些
ps:如果使用普通for循环遍历LinkedList,其遍历速度将慢得令人发指。

CopyOnWriteArrayList
优点:
绝对的线程安全
缺点:
每次写操作都会伴随数组的复制,性能开销大
带来的两个很重要的分布式理念:
读写分离和最终一致

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章