JAVA集合:LinkedList源码解析

LinkedList

List中除了ArrayList最常用以外,LinkedList也比较常见,而且这两种list的实现方式不一样,具体实现看一下源码很容易就理解了(以下源码来自jdk1.8.0_20)

继承结构
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
复制代码

LinkedList继承了AbstractSequentialList,实现了List接口、Deque接口和java.io.Serializable接口,从它的继承机构就能看出它是一种队列的实现方式。

成员变量
  • 大小size
    transient int size = 0;

  • 第一个节点
    transient Node<E> first;

  • 最后一个节点
    transient Node<E> last;

Node结构

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;
    }
}
复制代码
构造函数

LinkedList有一个空参构造函数和一个集合参数构造函数。

public LinkedList() {
}

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);  //把集合中所有节点添加到list中
}
复制代码
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) {    //把集合c插入到最后面
        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节点是最后一个插入的节点
        last = pred;
    } else {
        pred.next = succ;
        succ.prev = pred;
    }

    size += numNew;     //list大小加上增加集合的元素数量
    modCount++;         //修改次数加1
    return true;
}

private void checkPositionIndex(int index) {
    if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
    return index >= 0 && index <= size;     //比较index在0到size之间
}

/**
*   获取下标为index的节点
*/
Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {      //如果index在前半部分,则从前循环
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {                        //如果index在后半部分,则从后循环
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}
复制代码
主要方法
  • add方法
    • add(E e),一个参数方法,默认添加到list最后面
    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);     //新建node节点,pre指向list中的last节点
        last = newNode;
        if (l == null)          //如果list为空,新增节点赋值给first
            first = newNode;
        else
            l.next = newNode;   //如果不为空,list中的last指向新增节点,完成新增节点动作
        size++;
        modCount++;
    }
复制代码
    • add(int index, E element),把元素element添加到下标index位置
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)  //如果index等于size,添加到list最后面
            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);  //插入到当前index上的节点和它的pred节点中间
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
复制代码
  • 还有增加集合的add方法,上面介绍过了,以及实现的Deque接口的addFirst(E e)和addLast(E e)方法
    • addAll(Collection<? extends E> c)
    • addAll(int index, Collection<? extends E> c)
    • addFirst(E e) linkFirst插入到最前面
    • addLast(E e) 和add(E e)一样
    private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
复制代码
  • get方法
    • get(int index) //获取下标index上的元素
    • getFirst() //获取第一个元素(first节点的值)
    • getLast() //获取最后一个元素(last节点的值)
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;    //node(index)获取下标index的node节点
    }
复制代码
public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
复制代码
public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
复制代码
  • remove方法
    • remove()删除第一个元素,直接调用的removeFirst()方法
    • remove(int index)删除下标index上的元素,如果下边越界,会抛IndexOutOfBoundsException异常
    • remove(Object o)删除第一个匹配到的元素o
    • removeFirst()删除第一个元素(如果list为空,会抛出NoSuchElementException异常)
    • removeFirstOccurrence(Object o)直接调用remove(o)
    • removeLast()删除最后一个元素(如果list为空,会抛出NoSuchElementException异常)
    • removeLastOccurrence(Object o)删除最后一个匹配到的元素
    public E remove() {
        return removeFirst();
    }
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(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; // 断开删除节点的连接,帮助垃圾回收
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }
    
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index)); //删除下标index上的节点
    }
    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节点,即删除当前节点
            first = next;
        } else {
            prev.next = next;   //否则,前一个节点的next指向下一个节点
            x.prev = null;
        }

        if (next == null) { //如果是尾节点,last指向前一个节点,即删除当前节点
            last = prev;
        } else {
            next.prev = prev;   //否则,下一个节点的prev指向前一个节点
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
    
    /**
    * 删除list中最前面的元素o(如果存在),从first节点往后循环查找
    * null的equals方法总是返回false,所以需要分开判断
    */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {    //从first节点往后循环,删除第一个匹配的元素,结束循环
                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 removeFirstOccurrence(Object o) {
        return remove(o);
    }
    
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    
    public boolean removeLastOccurrence(Object o) { //删除list中最后面的元素o(如果存在),从last节点往前循环查找即可
        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;
    }
复制代码
  • peek方法,返回list中的第一个元素,不删除,如果list为空,返回null
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }
复制代码
  • poll方法,返回list中的第一个元素,并删除,如果list为空,返回null
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
复制代码
    • peekFirst(),同peek()
    • peekLast(),返回最后一个元素,不删除
    • pollFirst(),同poll()
    • pollLast(),返回最后一个元素,并删除
  • push(E e)方法,添加元素,

    public void push(E e) {
        addFirst(e);
    }
复制代码
  • pop()方法,删除list中的第一个元素,如果list为空,抛出NoSuchElementException异常
    public E pop() {
        return removeFirst();
    }
复制代码
  • clear()方法,删除list中的所有元素
    public void clear() {
        for (Node<E> x = first; x != null; ) {  //循环list,把item、next、prev赋值为null,帮助垃圾回收
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }
复制代码
  • clone()方法,复制一个相同的list
    public Object clone() {
        LinkedList<E> clone = superClone();

        // 初始化list的状态
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // 把原list中的元素复制到新list中
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }
    
    private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }
复制代码
  • contains(Object o)方法,判断list中是否包含元素o
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
复制代码
  • indexOf(Object o)方法,返回元素o的下标
    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;
    }
复制代码
  • set(int index, E element)方法,给下标index上的元素赋值,返回原有的值
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }
复制代码
  • size方法,返回list大小
    public int size() {
        return size;
    }
复制代码
  • toArray()方法,把list中的元素复制到新数组中并返回该数组
    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)方法,把list中的元素复制到指定的数组中
    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;
    }
复制代码
ListIterator迭代器
  • listIterator(int index)
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }
复制代码

LinkedList中的迭代器,比较简单,使用next、nextIndex、lastReturned变量做个标记。

    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是以数组的方式实现,而LinkedList是以链表的方式实现
  • LinkedList的源码相对简单,很容易理解它的存储结构,提供的方法以及实现。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值