JDK1.8 LinkedList源码

LinkedList

1.构造方法

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    transient int size = 0;
    transient Node<E> first;
    transient Node<E> last;
     
    public LinkedList() {
    }
 
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
}

首先初始化链表的大小为0,并且定义了头和尾的节点实现双向链表。

链表的每一个节点都是一个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;
    }
}
    
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;
    }
}   

每一个Node都有指向下一个和上一个的Node引用实现双向的索引,item用于存放对象或是值,而通过node()这一方法可以看到双向链表对比单向链表在效率上的优越性,可以通过判断index在前半部还是后半部决定从头遍历还是从尾部遍历,并返回指定下标上的Node节点。

回到构造方法,首先无参构造就是什么也不做。

通过集合来构造linkedlist会调用addAll方法,把集合里的元素全部从尾部插入,代码如下:

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

首先这里涉及到一个checkPositionIndex方法,这个方法的代码很简单,就是检查这个下标是否是一个合法的位置下标,与数组检查下标越界的想法一样,代码如下:

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

private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

接着将集合转换为数组,如果数组的长度为0,说明原集合无元素或转化失败,返回构造失败,可以看到构造方法调用的addall直接传入了size作为参数,那么查看size==index的代码块,可以了解pred(previous node)指向链表尾部,而succ也就是指向下一个节点的变为了null,这就确保了是插入尾部的,接下来的逻辑比较繁琐但是也比较简单,就不详细解释了,就是遍历数组,然后插入,如果first为null说明linkedlist为空,如果succ为null说明是从尾部插入,然后根据情况连接节点。

2.增加元素的三个方法

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

第一个很简单,就是尾插,一个局部变量引用尾节点,接着把新的节点赋值给实际的尾节点,最后判断如果尾节点为null,说明原始list为空,那么首节点也是新节点,不然原来尾节点的next指向新节点。

public void add(int index, E element) {
        checkPositionIndex(index);
 
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
 
 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++;
    }

第二个add是指定位置插入,首先判断是否下标合法,如果指定的位置是尾部,那么调用上文的linklast,不然调用linkbefore,顾名思义就是在指定节点前插入,首先中间插入节点,必然要让指定节点的前一节点的next指向新节点并且原节点的prev指向新节点,所以要有两个节点的引用,这里的final Node<E> pred = succ.prev;就是取得前一节点,接着判断如果前一节点为null,说明你指定的节点是头节点,那么使头节点指向新节点,不然前节点的next指向新节点。

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

addall已经解释过了。

3.删除节点的三个方法

public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
 
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;
    }

这里又涉及了一个check方法,是确保index是一个合法的元素下标,代码如下:

private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }
    
private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

这个checkelement和checkposition的差别在于index是否可以等于size,插入节点指定是插入的位置,实际上linkedlist的下标也是从0开始的,而插入方法可以看到是linkbefore,在指定节点前插入,所以当index==size的时候,实际这个index下是没有元素的,用于插入尾部,因为尾部不是任何一个节点的前节点。而删除、获取、更改等方法必须对一个实际的节点操作,那么你的index下必须有一个实际的节点,故而不能等于size。

然后就可以想象,如果要在一串珠子里取走一颗珠子,那么防止珠子断裂,取走的珠子的前一颗和后一颗必须相连,这里也是如此,删除节点的操作实际上设计三个节点的变动,方法首先获取了指定节点、指点节点的前节点和指定节点的后节点,这是判断如果前节点为null,那么说明指点节点是头节点,那么头节点重新指向指点节点的后节点,如果后节点为null,说明指定节点为尾节点,那么尾节点重新指向指定节点的前节点,这里所有赋值null的操作都是为了取消强引用,让gc回收空间。

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

理解了链表的删除机制,那么这个删除就很简单了,无非就是遍历了链表并删除了第一个符合的节点。

public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

这里同样的,不过更加复杂了一点,在遍历的同时要检查是否包含在c集合内。

4.修改元素

public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

就是获取节点然后更改值并返回原值

5.查找元素

public E get(int index) {
    checkElementIndex(index);//判断是否越界 [0,size)
    return node(index).item; //调用node()方法 取出 Node节点,
}
 
 
 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;
    }
 
 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;
    }

很简单,按下标找就是直接返回值,indexof和lastindexof就是一个从头遍历一个从尾遍历,并返回第一个符合的下标

6.迭代器

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

    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;
            nextIndex++;
            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;
            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);
            nextIndex++;
            expectedModCount++;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }

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

这个迭代器和在arraylist里的迭代器差不多,对多线程干扰的检查做了封装方便调用,其中的add remove等和原先的add和remove等方法差不多,无非多了改动检查,froEachRemaining暂时看不懂,留待以后更新。

除此之外还有一个反向的迭代器,也很简单,就是正向迭代的next和previous反一下,代码很简短,如下:

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

学习自:https://www.cnblogs.com/wjtaigwh/p/9883828.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值