Collection类

Set:

TreeSet

基于红黑树实现,支持有序性操作,例如根据一个范围查找元素的操作。查找效率不如 HashSet,HashSet 查找的时间复杂度为 O(1),TreeSet 则为 O(logN)

HashSet

基于哈希表实现,支持快速查找,不支持有序性操作。并且失去了元素的插入顺序信息,即:使用 Iterator 遍历 HashSet 得到的结果是不确定的

LinkedHashSet

具有 HashSet 的查找效率,且内部使用双向链表维护元素的插入顺序

List:

ArrayList:

基于动态数组实现,支持随机访问

ArrayList 实现了 List 接口,是顺序容器,允许放入 null 元素,底层由数组实现,与 Vector 大致相同,但未实现同步。每个 ArrayList 都有一个容量(capacity),表示底层数组的实际大小,容器内存储元素的个数不能多于当前容量。党项容器中添加元素时,如果容量不足,容器会自动增大底层数组的大小。

size(),isEmpty(),get(),set()方法均能在常数时间内完成,add() 方法的时间开销跟插入位置有关,addAll() 方法发时间开销跟添加元素的个数成正比。其余方法大都是线性时间。

为追求效率,ArrayList 没有实现同步(synchronized),如果需要多个线程并发访问,用户可以手动同步,也可使用Vector替代

ArrayList的实现:
底层数据结构:
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
初始化数组:
	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;
    }
自动扩容:

每当数组添加元素时,都需要检查添加后元素的个数是否会超出当前数组的长度,若超出,数组将会进行扩容,以满足添加数据的需求。数据扩容通过一个公开的方法 ensureCapacity(int minCapacity) 实现。在实际添加大量元素前,也可以使用 ensureCapacity 来手动添加ArrayList 实例的容量,以减少递增式再分配的数量。

数组进行扩容时,会将原本数组中的元素重新拷贝一份到新的数组中,每次数组扩容为原容量的 1.5 倍。

	public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

	private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

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

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
add(),addAll()

add(E e)add(int index, E e)。都是向容器中添加新元素,这可能会导致 capacity 不足,因此需要在添加元素之前进行剩余空间检查,如果需要则自动扩容。扩容操作通过 grow() 方法来完成。

add(int index, E e) 需要对元素进行移动后完成插入操作,即该方法有着线性的时间复杂度

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    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++;
    }

addAll() 方法能够一次添加多个元素,根据位置不同分为:在末尾添加的 addAll(Collection<? extends E> c) 方法,从指定位置开始插入的 public boolean addAll(int index, Collection<? extends E> c) 方法。跟 add() 方法类似,在插入之前也需要进行空间检查,如果需要则自动扩容;如果从指定位置插入,也需要移动元素。addAll 的时间复杂度不仅跟插入元素的多少有关,也跟插入的位置有关。

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    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;
    }

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    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;
    }
set()

直接对数组的指定位置赋值

    public E set(int index, E element) {
        rangeCheck(index); // 下标越界检查

        E oldValue = elementData(index);
        elementData[index] = element; //赋值到指定位置
        return oldValue;
    }
get()
	public E get(int index) {
    	rangeCheck(index);
    	return (E) elementData[index];//注意类型转换
	}
remove()

remove(int index) 删除指定位置的元素,remove(Object o) 删除第一个满足 o.equal(element)Data[index] 的元素。删除操作是 add() 操作的逆过程,需要将删除点之后的元素向前移动一个位置。注意:为了让GC起作用,必须显式的为最后一个位置赋 null 值。

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

**有了垃圾收集器并不意味着一定不会有内存泄漏。**对象能否被GC的依据是是否还有引用指向它,上面代码若不是手动赋 null 值,除非对应位置被其他元素覆盖,否则原来的对象就一定不会被回收

trimToSize()

将底层数组的容量调整为当前列表保存的实际元素的大小

	public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
indexOf(), lastIndexOf()

获取元素的第一次出现的 index;获取元素最后一次出现的 index

    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;
    }
Fail-Fast 机制:

快速失败的机制通过记录 modCount 参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。

Vector

和 ArrayList 类似,但它线程安全

LinkedList:

基于双向链表实现,只能顺序访问,但是可以快速的在链表中间插入和删除元素。LinkedList还可以用作栈、队列和双向队列。

LinkedList同时实现了List接口和Deque接口,即:它既可看作一个顺序容器,又可看作一个队列(Queue),同时可以看作一个栈(Stack)。关于栈或队列,首选是ArrayDeque,它有着比LinkedList(当作栈或队列使用时)更好的性能

LinkedList中所有跟下标有关的操作都是线性时间,而在首段或者末尾删除元素只需要常数时间。为追求效率 LinkedList 没有实现同步(synchronized),如果需要多个线程并发访问,可以先采用 Collections.synchronizedList() 方法对其进行包装

LinkedList的实现:

底层数据结构

LinkedList底层通过双向链表实现,双向链表的每个节点用内部类Node表示。LinkedList通过 firstlast 引用分别指向链表的第一个和最后一个元素。当链表为空的时候 firstlast 都指向 null

	transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

其中Node是私有的内部类:

    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;
        }
    }
构造函数
    /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
getFirst(), getLast()

获取第一个元素,获取最后一个元素:

    /**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
removeFirst(), removeLast(), remove(e), remove(index)

remove() 方法:一个删除跟指定元素相等的第一个元素 remove(Object o),另一个删除指定下标处的元素 remove(int index)

删除元素 - 指的是删除第一次出现的这个元素,如果没有这个元素,则返回 false;判断的依据是equals方法,如果equals,则直接unlink这个node;由于LinkedList可存放null元素,故也可以删除第一次出现的null的元素;

    /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    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;
    }

    /**
     * Unlinks non-null node x.
     */
    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;
    }

remove(int index) 使用的是下标计数,只需要判断该index是否有元素即可,如果有则直接unlink这个node。

    /**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

删除head元素:

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
    
    /**
     * Unlinks non-null first node f.
     */
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

删除last元素:

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }
add()

add()方法有两个版本,一个是 add(E e),该方法在LinkedList的末尾插入元素,因为有 last 指向链表末尾,在末尾插入元素的花费是常数时间。一个是 add(int index, E element),该方法是在指定下表处插入元素,需要先通过线性查找找到具体位置,然后修改相关引用完成插入操作。

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    
    /**
     * Links e as last element.
     */
    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++;
    }

add(int index, E element),当 index == size 时,等同于add(E e);否则,分为两步操作:1. 根据index找到要插入的位置,即 node(index) 方法;2. 修改引用,完成插入操作

    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

由于为双向链表,node(int index) 可以从开始往后找,也可以从结尾往前找,具体方向取决于条件 index < (size >> 1),也即是index是靠近前端还是后端。也可看出,LinkedList通过index检索元素的效率低于ArrayList。

    /**
     * Returns the (non-null) Node at the specified element 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;
        }
    }
addAll()

addAll(index, c) 实现方式并不是直接调用add(index, e)来实现,主要是因为效率的问题,另一个是fail-fast中modCount只会增加1次。

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the specified
     * collection's iterator.  The behavior of this operation is undefined if
     * the specified collection is modified while the operation is in
     * progress.  (Note that this will occur if the specified collection is
     * this list, and it's nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element
     *              from the specified collection
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    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;
    }
clear()

为了让GC更快可以回收放置的元素,需要将node之间的引用关系赋空

    /**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }
Positional Access 方法

通过index获取元素

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

将某个位置的元素重新赋值

    /**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

将元素插入到指定index位置:

    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

删除指定位置的元素:

    /**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

其他位置的方法:

    /**
     * Tells if the argument is the index of an existing element.
     */
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
查找操作:

本质是查找元素的下标;

查找第一次出现的index,如果找不到返回-1;

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the first occurrence of the specified element in
     *         this list, or -1 if this list does not contain the element
     */
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

查找最后一次出现的index,如果找不到返回-1;

    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the last occurrence of the specified element in
     *         this list, or -1 if this list does not contain the element
     */
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

Stack && Queue:

Queue

Queue接口继承自Collection接口,除了最基本的Collection的方法之外,还支持额外的insertion,extraction和inspection操作。这里有两组格式,共6个方法,一组是抛出异常的实现;另外一组是返回值的实现(没有则返回null)。

Throws exceptionReturn special value
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()

Deque:

Deque 是“double ended queue”,表示双向的队列,英文读作“deck”,Deque 继承自 Queue 接口,除了支持 Queue 的方法之外,还支持 insertremove,和examine 操作,由于Deque是双向的,所以可以对队列的头和尾都进行操作,它同时也支持两组格式,一组是抛出异常的实现;另外一组是返回值的实现(没有则返回null)。共12个方法如下:

First Element - HeadLast Element - Tail
Throw exceptionSpecial valueThrow exceptionSpecial value
insertaddFirst(e)offerFirst(e)addLast(e)offerLast(e)
RemoveremoveFirst()pollFirst()removeLast()pollLast()
ExaminegetFirst()peekFirst()getLast()peekLast()

当把 Deque 当作FIFO的 Queue 来使用时,元素是从 Deque 的尾部添加,从头部进行删除的;所以 Deque 的部分方法是和 Queue 是等同的。

Deque既可以当作栈使用,也可以当作队列使用。

Deque与Queue对应的接口

Queue MethodEquivalent Deque Method说明
add(e)addLast(e)向队尾插入元素,失败则抛出异常
offer(e)offerLast(e)向队尾插入元素,失败则返回 false
remove()removeFirst()获取并删除队首元素,失败则抛出异常
poll()pollFirst()获取并删除队首元素,失败则返回 null
element()getFirst()获取但不删除队首元素,失败则抛出异常
peek()peekFirst()获取但不删除队首元素,失败则返回 null

Deque与Stack对应的接口:

Stack MethodEquivalent Deque Method说明
push(e)addFirst(e)向栈顶插入元素,失败则抛出异常
offerFirst(e)向栈顶插入元素,失败则返回false
pop()removeFirst()获取并删除栈顶元素,失败则抛出异常
pollFirst()获取并删除栈顶元素,失败则返回null
peek()peekFirst()获取但不删除栈顶元素,失败则抛出异常
peekFirst()获取但不删除栈顶元素,失败则返回null

ArrayDeque和LinkedList是Deque的两个通用实现。ArrayDeque底层通过数组实现,为了满足可以同时在数组两端插入或删除元素的需求,该数组还必须是循环的,即 循环数组,也就是说数组的任何一点都可能被看作起点或者终点。ArrayDeque是非线程安全的,当多个线程同时使用的时候,需要程序员手动同步;另外,该容器不允许放入 null 元素

ArrayDeque中 head 指向首段第一个有效元素,tail 指向尾端第一个可以插入元素的空位。因为是循环数组,所以 head 不一定总等于0,tail 也不一定总是比 head 大。

方法剖析:

addFirst()

addFirst(E e) 的作用是在Deque的首端插入元素,也就是在 head 的前面插入元素,在空间足够且下标没有越界的情况下,只需要将 elements[--head] = e 即可。

在这里插入图片描述

实际需要考虑:1. 空间是否够用,2. 下表是否越界。如图所示,当 head 为 0 时调用 addFirst(),虽然空间还有剩余,但 head 为 -1,下标越界。因此通过计算下标:head = (head - 1) & (elements.length - 1) 解决下标越界问题,**这段代码相当于取余,同时解决了 head 为负值发情况。**因为 elements.length 必须是 2 的指数倍,elements - 1 就是二进制低位全为1,跟 head - 1 相与后起到了取模的作用,如果 head - 1为负数,则相当于取 elements.length 的补码:

    /**
     * Inserts the specified element at the front of this deque.
     *
     * @param e the element to add
     * @throws NullPointerException if the specified element is null
     */
    public void addFirst(E e) {
        if (e == null) // 不允许放入null
            throw new NullPointerException();
        elements[head = (head - 1) & (elements.length - 1)] = e; // 下标是否越界
        if (head == tail) // 空间是否够用
            doubleCapacity(); // 扩容
    }

由上述代码可见:空间问题是在插入之后解决的,因为 tail 总是指向下一个可插入的空位,也就意味着 elements 数组至少有一个空位,所以插入元素的时候不用考虑空间问题。

扩容函数 doubleCapacity() 其逻辑是申请一个更大的数组(原数组的两倍),然后将原数组复制过去。

    /**
     * Doubles the capacity of this deque.  Call only when full, i.e.,
     * when head and tail have wrapped around to become equal.
     */
    private void doubleCapacity() {
        assert head == tail;
        int p = head;
        int n = elements.length;
        int r = n - p; // 获取head右边元素的个数
        int newCapacity = n << 1; // 新数组的长度为原来的两倍
        if (newCapacity < 0)
            throw new IllegalStateException("Sorry, deque too big");
        Object[] a = new Object[newCapacity];
        System.arraycopy(elements, p, a, 0, r); //复制head右边的元素,对应新数组的下标为[0, r)
        System.arraycopy(elements, 0, a, r, p); //复制head左边的元素,对应新数组的下标为[r, n)
        elements = a;
        head = 0;
        tail = n;
    }
addLast()

addLast(E e) 的作用是在Deque的尾端插入元素,也就是在 tail 的位置插入元素,由于 tail 总是指向下一个可以插入的空位,因此只需要 elements[tail] = e 即可,插入完成后再检查空间,如果空间已经用光,则调用 doubleCapacity() 进行扩容

    /**
     * Inserts the specified element at the end of this deque.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     * @throws NullPointerException if the specified element is null
     */
    public void addLast(E e) {
        if (e == null) //不允许放入 null
            throw new NullPointerException();
        elements[tail] = e; // 赋值
        if ( (tail = (tail + 1) & (elements.length - 1)) == head) // 下标越界处理
            doubleCapacity(); // 扩容
    }
pollFirst()

pollFirst() 的作用是删除并返回Deque首段元素,也即是 head 位置处的元素。如果容器不空,只需要直接返回 elements[head] 即可,当然还需要处理下标的问题。由于 ArrayDeque 中不允许放入 null,当 elements[head] == null 时,意味着容器为空。

    public E pollFirst() {
        int h = head;
        E result = (E) elements[h];
        // Element is null if deque empty
        if (result == null)
            return null;
        elements[h] = null;     // Must null out slot
        head = (h + 1) & (elements.length - 1); // 下标越界处理
        return result;
    }
pollLast()

pollLast() 的作用是删除并返回Deque尾端元素,也就是 tail 位置前面的那个元素

    public E pollLast() {
        int t = (tail - 1) & (elements.length - 1);
        E result = (E) elements[t];
        if (result == null)
            return null;
        elements[t] = null;
        tail = t;
        return result;
    }
peekFirst()

peekFirst() 的作用是返回但不删除Deque首端元素,也即是 head 位置处的元素,直接返回 elements[head] 即可。

    public E peekFirst() {
        // elements[head] is null if deque empty
        return (E) elements[head];
    }
peekLast()

peekLast 的作用是返回但不删除Deque尾端元素,也即是 tail 位置前面的那个元素

	public E peekLast() {
        return (E) elements[(tail - 1) & (elements.length - 1)];
    }

PriorityQueue

PriorityQueue,即优先队列;作用是能保证每次取出的元素都是队列中权值最小的(Java的优先队列每次取最小元素,C++的优先队列每次取最大元素)。元素大小的判断可以通过元素本身的自然顺序,也可以通过构造时传入的比较器

Java中PriorityQueue实现了Queue接口,不允许放入 null 元素;其通过完全二叉树实现的小顶堆(任意一个非叶子节点的权值,豆瓣不大于其左右子结点的权值),也就意味着可以通过数组来作为PriorityQueue的底层实现。

在这里插入图片描述

由图可发现父子结点之间的关系为:

leftNo = parentNo * 2 + 1

rightNo = parentNo * 2 + 2

parentNo = (nodeNo - 1) / 2

PriorityQueue的 peek()element 操作是常数时间,add()offer(),无参数的 remove() 以及 poll() 方法的时间复杂度都是log(N).

方法剖析

add() 和 offer()

add(E e) 和 offer(E e) 的语义相同,都是向优先队列中插入元素,只是 Queue 接口规定二者对插入失败的处理不同,前者插入失败时抛出异常,后者返回 false

新加入的元素可能会破坏小顶堆的性值,因此需要进行必要的调整

    public boolean add(E e) {
        return offer(e);
    }

    /**
     * Inserts the specified element into this priority queue.
     *
     * @return {@code true} (as specified by {@link Queue#offer})
     * @throws ClassCastException if the specified element cannot be
     *         compared with elements currently in this priority queue
     *         according to the priority queue's ordering
     * @throws NullPointerException if the specified element is null
     */
    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1); // 扩容
        size = i + 1;
        if (i == 0) //队列原来为空,这是插入的第一个元素
            queue[0] = e; 
        else
            siftUp(i, e); //调整
        return true;
    }

    /**
     * Increases the capacity of the array.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // Double size if small; else grow by 50%
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // overflow-conscious code
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        queue = Arrays.copyOf(queue, newCapacity);
    }

    private void siftUp(int k, E x) {
        if (comparator != null) // 比较器不为空时,使用比较器比较
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

    private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0) // 调用比较器的比较方法
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

新加入的元素破坏了小顶堆的性值时,调整过程为:从 k 指定的位置开始,将 x 逐层与当前点的 parent 进行比较并交换,直到满足 x >= queue[parent] 为止。这里的比较可以是元素的自然顺序,也可以是依靠比较器的顺序。

element() 和 peek()

element()peek() 的语义完全相同,都是获取但不删除队首元素,也就是队列中权值最小的那个元素,二者唯一的区别是当方法失败时前者抛出异常,后者返回 null。根据小顶堆的性值,堆顶的那个元素就是全局最小的那个;由于堆用数组表示,根据下标关系, 0 下标处的那个元素即是堆顶元素。所以直接返回数组 0 下标处的那个元素即可

    public E peek() {
        return (size == 0) ? null : (E) queue[0];
    }
remove() 和 poll()

remove()poll()方法的语义也完全相同,都是获取并删除队首元素,区别是当方法失败时前者抛出异常,后者返回null

在这里插入图片描述
----------------------------分割线----------------------------

    public boolean remove(Object o) {
        int i = indexOf(o);
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }

    public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }

上述代码首先记录 0 下标处的元素,并用最后一个元素替换 0 下标位置的元素,之后调用 siftDown() 方法对堆进行调整,最后返回原来 0 下标处的那个元素(也就是最小的那个元素)。siftDown(int k, E e) 方法的作用:从 k 指定的位置开始,将 x 逐层向下与当前点的左右孩子中较小的那个交换,直到 x 小于或等于左右孩子中的任何一个为止。

    private void siftDownComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>)x;
        int half = size >>> 1;        // 无符号右移
        while (k < half) {
            // 首先找到左右孩子中较小的那个,记录到c中,并用child记录其下标
            int child = (k << 1) + 1; // assume left child is least
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
                c = queue[child = right];
            if (key.compareTo((E) c) <= 0)
                break;
            queue[k] = c; //然后用c取代原来的值
            k = child;
        }
        queue[k] = key;
    }
remove(Object o)

remove(Object o) 方法用于删除队列中跟 o 相等的某一个元素(如果有多个相等,只删除一个),该方法不是Queue接口内的方法,二十Collection接口的方法。由于删除操作会改变队列结构,所以要进行调整;又由于删除元素的位置可能是任意的,所以调整过程比其他函数稍加繁琐。具体来说,remove(Object o) 可以分为两种情况:1. 删除的是最后一个元素。直接删除即可,不需要调整。2. 删除的不是最后一个元素,从删除点开始以最后一个元素为参照调用一次 siftDown() 即可。

    public boolean remove(Object o) {
        int i = indexOf(o);  // 定位第一个满足o.equals(queue[i])元素的下标
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }
    
    private E removeAt(int i) {
        // assert i >= 0 && i < size;
        modCount++;
        int s = --size;
        if (s == i) // removed last element
            queue[i] = null;
        else {
            E moved = (E) queue[s];
            queue[s] = null;
            siftDown(i, moved);
            if (queue[i] == moved) {
                siftUp(i, moved);
                if (queue[i] != moved)
                    return moved;
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值