java集合框架之List集合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011456867/article/details/86414672

list集合是工作中使用最频繁的一种集合。它是一种有序的集合结构。可以用于存储重复的元素。通过索引位置我们可以快速的定位元素进行操作。他的实现类主要有三个ArrayList,LinkedList,Vector。

  1. ArrayList
    ArrayLis是使用最频繁的一种集合。它是可以动态增长和缩减的索引序列,它是基于数组实现的List类,为什么说它是基于数组实现的呢我们可以看JDK的源码进行分析。
//我们先查看ArrayList定义的变量
transient Object[] elementData; // non-private to simplify nested class access
//再看其中比较重要的构造方法
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(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类的过程中。实际上是创建了一个数组。这个数据根据构造方法进行判断。
   // 如果传入的是长度。则根据长度构造空数组。如果传入的是集合。则将集合元素拷贝进创建的数组结构中。
   // 这里有个需要注意的是elementData变量,它是用transient 进行了修饰。我们知道这个关键字的作用是不被序列化。
   // 为什么这个变量特意用这个修饰呢。由于在ArrayList中的elementData这个数组的长度是变长的,java在扩容的时候,有一个扩容因
    //子,也就是说这个数组的长度是大于等于ArrayList的长度的,我们不希望在序列化的时候将其中的空元素也序列化到磁盘中去,
    //所以需要手动的序列化数组对象,所以使用了transient来禁止自动序列化这个数组
    //下面再看它的添加方法
    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    private void grow(int minCapacity) {
        // overflow-conscious code
        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);
    }
    //在ArrayList进行添加元素的时候。先进行判断集合长度是否为0,如果为0则传入默认值10进行扩容。如果长度不为0.则进行长度
  //  判断。如果数组未饱和则至今将元素放入。如果长度超出则进行扩容。查看grow()方法我们可以看出通过 Arrays.copyOf()
    //方法将创建一个原来长度1.5倍的新数组。并将元素复制进去。
  // 另外还有一个添加方法也用的较多
   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;
    }
    同样也会造成数组元素位置的重新调整。
  1. LinkedList
    LinkedList类是双向列表,列表中的每个节点都包含了对前一个和后一个元素的引用.类是双向列表,列表中的每个节点都包含了对前一个和后一个元素的引用。
//先看他的2个构造方法
public LinkedList() {
    }
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;
        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }
        size += numNew;
        modCount++;
        return true;
    }
    //通过这两个构造方法我们可以看出这两个集合有很大的不同它不再是采用数组进行存储了。而是用Node存了元素。
    //每个Node记录了上一个元素以及下一个元素。形成了类似锁链的结构。
   // 再看其添加和删除的方法
    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++;
    }
   // 将每个新的元素都加入到原来锁链的下一个元素中。并将集合的last变量赋值为最新的元素Node。
    //如果是按位置进行插入
    public void add(int index, E element) {
        checkPositionIndex(index);
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    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;
        }
    }
    //它是先从头开始进行链式查找。找到索引对应的元素。不能像ArrayList一样直接定位元素地址。
    //找到元素以后对元素的上个元素和下个元素进行替换。在锁链中加入了一个新的环扣。而其他的锁链并不会发生变化。
    //不需要像ArrayList一样进行位置调整。
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
    //再看其移除方法
    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;
    }
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
   // 也是通过锁链查找到元素对应的node并将node的上下两个元素的位置替换。解除掉删除元素的连接绑定。
    //不会对其他元素造成影响
所以通过这几个方法的分析我们可以得出这两种集合的特点
1.对于随机访问的get和set方法,ArrayList要优于LinkedList,因为LinkedList要从头开始查找
2.对于新增和删除操作add和remove,LinkedList比较占优势,因为ArrayList要移动很多数据
3.ArrayList的空间浪费主要体现在在list列表的结尾预留一定的容量空间,
而LinkedList的空间花费则体现在它的每一个元素都需要消耗相当的空间。
  1. Vector
    Vector与ArrayList一样,也是通过数组实现的,不同的是它支持线程的同步。
//先看其构造方法
	protected int capacityIncrement;
	public Vector() {
        this(10);
    }
    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }
  	public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }
	 public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }
    //不同于ArrayList。它提供了四种构造方法但是其实现还是依靠数组进行实现的。
    //其中有个参数capacityIncrement。这个参数通过查询其使用。发现是用于扩容的我们查看grow()。
   // 看到其扩容计算方式:int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
   // 是100%进行扩容的不同于ArrayList的50%。
    //查看其添加方法
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
    }
    //其方法和ArrayList的实现是基本一致的。不容的在于方法用同步锁进行了锁定。不仅是添加方法。
   // 其它方法也进行了同步锁定。保证了线程安全。但是也降低了其性能

通过查询得知Vector还有一个子类Stack。它通过五个操作对类Vector进行了扩展 ,允许将向量视为堆栈。它提供了通常的push和pop操作,以及取堆栈顶点的peek方法、测试堆栈是否为空的empty方法、在堆栈中查找项并确定到堆栈顶距离的search方法。
这两个都是jdk1.0的过时API,应该避免使用。
如果需要集合保证线程安全推荐使用CopyOnWriteArrayList和ConcurrentLinkedQueue。这两个以后进行分析

猜你喜欢

转载自blog.csdn.net/u011456867/article/details/86414672