List学习笔记

List

特点:1.有序。2.可重复。

ArrayList:

底层是数组,数组是有下标的。

会自动扩容,底层默认初始化容量是10,扩大之后的容量预设是原来容量的一半(jdk 1.8)。以前好像是原容量的1.5倍

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

Vector:

底层也是数组,扩容可以通过构造函数设置。默认初始化容量也是10,扩容一倍原来容量(在没有设置capacityIncrement的情况下)

public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    /**
     * Constructs an empty vector with the specified initial capacity and
     * with its capacity increment equal to zero.
     *
     * @param   initialCapacity   the initial capacity of the vector
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * Constructs an empty vector so that its internal data array
     * has size {@code 10} and its standard capacity increment is
     * zero.
     */
    public Vector() {
        this(10);
    }
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);
    }

如何优化ArrayList和Vector?

尽量减少扩容操作,因为每次扩容都要拷贝数组(Arrays.copyof),拷贝数组很消耗内存,所以一般推荐在创建集合的时候指定初始化容量。

对比ArrayList,LinkedList,Vector?

Vector是线程安全的,效率很低,所以现在很少使用。

ArrayList适合查询,不适合频繁随机的增删元素。

LinkedList适合频繁的增删元素,不适合查询。

原文地址:https://www.cnblogs.com/i-love-kobe/p/5905023.html