List学习笔记

Posted Steve_Nash

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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适合频繁的增删元素,不适合查询。

 

以上是关于List学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

DOM探索之基础详解——学习笔记

「学习笔记」3.13代码学习

python学习笔记

Java学习笔记——泛型

学习笔记 链接

ReactJs学习笔记01