LinkedList源碼解析(二)

size()返回結合中存儲的節點數量java

public int size() {
        return size;
    }

add(E e)向集合末尾添加一個元素node

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

remove(Object o)移除一個元素數組

public boolean remove(Object o) {
        if (o == null) {//若是o是null
            for (Node<E> x = first; x != null; x = x.next) {//從第一個節點指針指向的節點開始循環
                if (x.item == null) {//比較節點的值,的內存地址
                    unlink(x);//取消節點
                    return true;//操做成功
                }
            }
        } else {//若是o是否是null
            for (Node<E> x = first; x != null; x = x.next) {//從第一個節點指針指向的節點開始循環
                if (o.equals(x.item)) {//調用o的equals方法和節點的值做比較
                    unlink(x);//取消節點
                    return true;//操做成功
                }
            }
        }
        return false;//操做失敗
    }

addAll(Collection<? extends E> c)向集合末尾加入集合c安全

public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

clear()清空集合ui

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; ) {//從first指針指向的節點開始循環
            Node<E> next = x.next;//獲取x的next
            x.item = null;//x的值置空
            x.next = null;//x的next置空
            x.prev = null;//x的prev置空
            x = next;//x賦值爲next下一次循環使用
        }
        first = last = null;//第一個節點指針和最後一個節點的指針置空
        size = 0;//數據長度0
        modCount++;//操做數不清空
    }

get(int index)獲取index索引節點數據線程

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

set(int index, E element)設置index索引處的節點位數爲element指針

public E set(int index, E element) {
        checkElementIndex(index);//index在範圍內
        Node<E> x = node(index);//獲取索引處的節點
        E oldVal = x.item;//獲取節點舊的值
        x.item = element;//給節點的值賦值新值
        return oldVal;//返回舊的值
    }

add(int index, E element)根據索引插入數據code

public void add(int index, E element) {
        checkPositionIndex(index);//index在範圍內

        if (index == size)/、若是索引位index等於數據長度
            linkLast(element);//尾插入
        else
            linkBefore(element, node(index));//不然插入在index索引對應節點以前
    }

remove(int index)移除索引index處的數據對象

public E remove(int index) {
        checkElementIndex(index);//index在範圍內
        return unlink(node(index));
    }

isElementIndex(int index)判斷參數是不是現有元素的索引索引

private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

isPositionIndex(int index)判斷參數是不是現有元素的索引(迭代器或添加操做)

private boolean isPositionIndex(int index) {
        return index >= 0 && index < size;
    }

構造一個IndexOutOfBoundsException詳細消息

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

lastIndexOf(Object o)返回指定元素最後一次出現的索引

public int lastIndexOf(Object o) {
        int index = size;//初始下標賦值
        if (o == null) {//o爲null
            for (Node<E> x = last; x != null; x = x.prev) {//last指針指向的節點開始向前循環
                index--;
                if (x.item == null)//節點的值做內存比較
                    return index;//返回下標
            }
        } else {//o不爲null
            for (Node<E> x = last; x != null; x = x.prev) {//last指針指向的節點開始向前循環
                index--;
                if (o.equals(x.item))//調用o的equals方法和節點的值比較
                    return index;
            }
        }
        return -1;
    }

peek()索但不刪除此列表的頭部(null返回null)

public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;//若是是null的話不返回對象,返回null
    }

element()檢索但不刪除此列表的頭部(null會拋出異常)

public E element() {
        return getFirst();
    }

getFirst()返回此列表中的第一個元素(null會拋出異常)

public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

poll()檢索並刪除此列表的頭部(null返回null)

public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);//不爲null時候,刪除並返回第一個節點
    }

remove()檢索並刪除此列表的頭部

public E remove() {
        return removeFirst();
    }

offer(E e)將指定的元素添加爲此列表的尾部

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

offerFirst(E e)在指定列表第一個節點前面插入e

public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

offerLast(E e)在指定列表最後一個節點後面插入e

public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

peekFirst()檢索但不刪除此列表的第一個節點(null返回null)

public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

peekFirst()檢索但不刪除此列表的最後一個節點(null返回null)

public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

pollFirst()檢索並刪除此列表的第一個節點(null返回null)

public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

pollLast()檢索並刪除此列表的第最後一個節點(null返回null)

public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

push(E e)將元素插入到第一個節點簽名

public void push(E e) {
        addFirst(e);
    }

pop()移除第一個節點

public E pop() {
        return removeFirst();
    }

removeFirstOccurrence(Object o)刪除此中第一次出現的指定元素

public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

removeLastOccurrence(Object o)刪除此中最後一次出現的指定元素

//和lastIndexOf相似,找到後直接調用unlink
 public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

ListIterator<E> listIterator(int index)返回集合迭代器

public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

迭代器類ListItr

private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;//最後返回的節點
        private Node<E> next;//下一個節點
        private int nextIndex;//下一個節點的索引
        private int expectedModCount = modCount;

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);//構造下一個節點的索引
            nextIndex = index;
        }

        public boolean hasNext() {
            return nextIndex < size;//判斷是否有下一個節點
        }

        public E next() {
            checkForComodification();//線程安全
            if (!hasNext())
                throw new NoSuchElementException();//迭代器到尾部

            lastReturned = next;//迭代器越過next
            next = next.next;//next賦值爲next的下一個節點
            nextIndex++;//下一個節點的索引+1
            return lastReturned.item;//返回迭代器越過節點的值
        }

        public boolean hasPrevious() {
            return nextIndex > 0;//是否有前一個節點
        }

        public E previous() {
            checkForComodification();//線程安全
            if (!hasPrevious())
                throw new NoSuchElementException();//迭代器到達頭部

            lastReturned = next = (next == null) ? last : next.prev;//若是是空返回last指針指向的節點(不理解)
            nextIndex--;//下一個節點索引自減
            return lastReturned.item;//返回迭代器越過節點的值
        }

        public int nextIndex() {
            return nextIndex;//返回下一個索引
        }

        public int previousIndex() {
            return nextIndex - 1;//返回上一個索引
        }

        public void remove() {
            checkForComodification();
            if (lastReturned == null)//迭代器沒有越過任何元素
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;//獲取迭代器越過節點的下一個節點
            unlink(lastReturned);//移除越過的元素
            if (next == lastReturned)//不理解爲何會進去
                next = lastNext;
            else
                nextIndex--;//下一個節點索引自減
            lastReturned = null;
            expectedModCount++;
        }

        public void set(E e) {
            if (lastReturned == null)//迭代器沒有越過任何元素
                throw new IllegalStateException();
            checkForComodification();//線程安全
            lastReturned.item = e;//迭代器越過節點的值
        }

        public void add(E e) {
            checkForComodification();//線程安全
            lastReturned = null;
            if (next == null)//尾巴插入
                linkLast(e);
            else
                linkBefore(e, next);//next節點前插入
            nextIndex++;//下一個節點的索引加1
            expectedModCount++;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {//下一個節點的索引小於節點數
                action.accept(next.item);//運行accept方法
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();//線程安全
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

descendingIterator()適配器經過ListItr.previous提供降序迭代器

public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

降序迭代器DescendingIterato(調用的就是ListItr,反着調用)

private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

superClone()超類複製

@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

clone()複製集合對象

public Object clone() {
        LinkedList<E> clone = superClone();

        // Put clone into "virgin" state
        clone.first = clone.last = null;//第一個節點和最後一個節點置空
        clone.size = 0;//數據數置0
        clone.modCount = 0;//操做數置0

        // Initialize clone with our elements
        for (Node<E> x = first; x != null; x = x.next)//從first節點開始循環初始化clone對象
            clone.add(x.item);

        return clone;
    }

toArray()返回集合元素組成的數組

public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

toArray(T[] a)返回集合元素組成的數組(傳入數組的類型)

@SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);//建立數組
        int i = 0;
        Object[] result = a;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }
相關文章
相關標籤/搜索