LinkedList分析

第1部分 LinkedList介绍

LinkedList简介

LinkedList实现List接口,内部元素是有序的。
LinkedList实现Deque接口,需要提供队列,以及双端队列里的两组增删索引方法,此外还有栈方法。
LinkedList实现Cloneable接口,需要提供clone方法。
LinkedList实现Serializable接口,需要提供序列化,反序列化方法。
LinkedList是双向链表结构,增删效率快,迭代效率慢,此外,迭代的方式只能通过链表挨个遍历。

LinkedList构造函数

修饰语和返回类型方法描述
publicLinkedList()默认构造方法
publicLinkedList(Collection<? extends E> c)传入集合的构造方法

LinkedList常用API

省略实现Deque的方法

修饰语和返回类型方法描述
booleancontains(Object o)是否包含元素o
intsize()获取容量
booleanadd(E e)在最后添加元素
booleanremove(Object o)移除元素o
booleanaddAll(Collection<? extends E> c)在最后添加集合c
booleanaddAll(int index, Collection<? extends E> c)在索引为index前添加集合c
voidclear()清空元素
Eget(int index)获取索引为index的元素
Eset(int index, E element)设置索引为index的元素为element
voidadd(int index, E element)在索引为index的元素前插入element
intindexOf(Object o)获取首个出现o的索引
voidclear()清空元素

第2部分 LinkedList数据结构

LinkedList的继承关系

java.lang.Object
   ↳     java.util.AbstractCollection<E>
         ↳     java.util.AbstractList<E>
               ↳    

public class LinkedList<E> extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable {}

2.2 LinkedList的关系图
在这里插入图片描述
图1 LinkedList的关系图

第3部分 LinkedList源码解析(基于JDK-8u201)

内部类 ListItr

private class ListItr implements ListIterator<E> {
	//上一个返回的元素
    private Node<E> lastReturned;
    //下一个元素
    private Node<E> next;
    //下一元素的索引
    private int nextIndex;
    //期待更改次数,用于支持fast-fail
    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();
		//把next返回回去,next后移
        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.item;
    }
    public boolean hasPrevious() {
        return nextIndex > 0;
    }

    public E previous() {
        checkForComodification();
        if (!hasPrevious())
            throw new NoSuchElementException();
		//如果next为null,返回LinkedList的尾指针
        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;
        //移除掉lastReturned
        unlink(lastReturned);
        if (next == lastReturned)
            next = lastNext;
        else
            nextIndex--;
        lastReturned = null;
        expectedModCount++;
    }
	//设置lastReturned里元素为e
    public void set(E e) {
        if (lastReturned == null)
            throw new IllegalStateException();
        checkForComodification();
        lastReturned.item = e;
    }
	//在next之前添加元素
    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();
    }
}

这个迭代器没什么特殊的,方法都是ListIterator的方法,只是迭代方式使用的是链表。

内部类 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节点是LinkedList的基本组成成员,具有向前和向后的两个引用(指针),构成一条双向链表。

内部类 DescendingIterator

//逆序迭代器
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();
    }
}

内部类 LLSpliterator

/** A customized variant of Spliterators.IteratorSpliterator */
//自定义的Spliterators.IteratorSpliterator,后者为Collection接口里的可分割迭代器
static final class LLSpliterator<E> implements Spliterator<E> {
    static final int BATCH_UNIT = 1 << 10;  // batch array size increment
    static final int MAX_BATCH = 1 << 25;  // max batch array size;
    final LinkedList<E> list; // null OK unless traversed
    Node<E> current;      // current node; null until initialized
    int est;              // size estimate; -1 until first needed
    int expectedModCount; // initialized when est set
    int batch;            // batch size for splits

    LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
        this.list = list;
        this.est = est;
        this.expectedModCount = expectedModCount;
    }
	//获取容量作为估计值
    final int getEst() {
        int s; // force initialization
        final LinkedList<E> lst;
        if ((s = est) < 0) {
            if ((lst = list) == null)
                s = est = 0;
            else {
                expectedModCount = lst.modCount;
                current = lst.first;
                s = est = lst.size;
            }
        }
        return s;
    }
    public long estimateSize() { return (long) getEst(); }
	//尝试切分
    public Spliterator<E> trySplit() {
        Node<E> p;
        int s = getEst();
        if (s > 1 && (p = current) != null) {
        	//确定切割范围
            int n = batch + BATCH_UNIT;
            if (n > s)
                n = s;
            if (n > MAX_BATCH)
                n = MAX_BATCH;
            Object[] a = new Object[n];
            int j = 0;
            do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
            current = p;
            batch = j;
            est = s - j;
            //返回一个ArraySpliterator迭代器,是数组形式的
            return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
        }
        return null;
    }
	//对剩下元素迭代
    public void forEachRemaining(Consumer<? super E> action) {
        Node<E> p; int n;
        if (action == null) throw new NullPointerException();
        if ((n = getEst()) > 0 && (p = current) != null) {
            current = null;
            est = 0;
            do {
                E e = p.item;
                p = p.next;
                action.accept(e);
            } while (p != null && --n > 0);
        }
        if (list.modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
	//处理单独元素
    public boolean tryAdvance(Consumer<? super E> action) {
        Node<E> p;
        if (action == null) throw new NullPointerException();
        if (getEst() > 0 && (p = current) != null) {
            --est;
            E e = p.item;
            current = p.next;
            action.accept(e);
            if (list.modCount != expectedModCount)
                throw new ConcurrentModificationException();
            return true;
        }
        return false;
    }
    public int characteristics() {
        return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
    }
}

可分割迭代器LLSpliterator跟其他可分割迭代器的最大的区别在于,它切分出来的迭代器为数组类型,而不再是链表,而且,如果一直切分下去,那么最初的迭代器,最终将分不到元素。如下

public class Test1 {
	public static void main(String[] args) {
		LinkedList<Integer> linkedList=new LinkedList<>();
		int n=10;
		for(int i=0;i<n;i++) {
			linkedList.add(i);
		}
		new Thread(new Mythread(linkedList.spliterator())).start();
	}
	static class Mythread implements Runnable{
		private Spliterator<Integer> spliterator;
		public Mythread(Spliterator<Integer> spliterator) {
			this.spliterator=spliterator;
		}
		@Override
		public void run() {
			//还可再分割
			Spliterator<Integer> subSpliterator;
			if((subSpliterator=spliterator.trySplit())!=null) {
				new Thread(new Mythread(subSpliterator)).start();
			}
			spliterator.forEachRemaining(s->System.out.println(Thread.currentThread().getName()+":"+s));
		}	
	}
}

从以下结果可以看出,没有出现Thread-0

Thread-2:2
Thread-3:1
Thread-1:5
Thread-4:0
Thread-1:6
Thread-2:3
Thread-2:4
Thread-1:7
Thread-1:8
Thread-1:9

LinkedList

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);
    }
    //在链表前插入元素e
    private void linkFirst(E e) {
        final Node<E> f = first;
        //构造方法Node<>(prev, e, next)
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        //f == null,也就是最开始first=last=null
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
	//在量表末尾插入元素
    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++;
    }
	//在succ节点前插入元素,succ != null,
	//由于这个方法不是public类型,因此,使用者是访问不到的,不会出问题
    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++;
    }
	//移除头节点
    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;
    }
	//移除尾节点
    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;
    }
	//移除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;
    }
	//获取首元素,以下为Deque接口提供的方法
    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;
    }
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    public void addFirst(E e) {
        linkFirst(e);
    }
    public void addLast(E e) {
        linkLast(e);
    }
    //以下两个为Colletion接口方法
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
    public int size() {
        return size;
    }
	//以下为Queue接口方法
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    //移除元素o,只能从头到尾遍历
    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 addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
	//在索引为index前添加集合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 {
        	//获取index处的节点
            succ = node(index);
            pred = succ.prev;
        }
		//遍历的过程,是将newNode插到pred后面,同时pred后移到newNode
        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;
        }
		//处理集合最后一个人元素跟succ的关系
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }
	//清空,让GC回收
    public void clear() {
        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++;
    }
	//获取index处的元素,注意,实现了该方法,就能调用父类的subList
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }
    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处的节点
    Node<E> node(int index) {
        // assert isElementIndex(index);
		//根据index跟size一半对比,看从头还是从尾开始遍历比较快
        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;
        }
    }
    //返回首个,只能从头到到遍历
    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;
    }
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }
    public E element() {
        return getFirst();
    }
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
    public E remove() {
        return removeFirst();
    }
    public boolean offer(E e) {
        return add(e);
    }
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }
    public void push(E e) {
        addFirst(e);
    }
    public E pop() {
        return removeFirst();
    }
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }
    //移除最后一个出现o的元素,跟上面的方法相比,返回类型不同
    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;
    }

    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }
    @SuppressWarnings("unchecked")
    private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }
	//克隆,实现Clonable接口方法
    public Object clone() {
        LinkedList<E> clone = superClone();

        // Put clone into "virgin" state
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        //把元素都添加进去
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }

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

    private static final long serialVersionUID = 876323262645176354L;
	//实现Serializable接口方法
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (Node<E> x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }
    @SuppressWarnings("unchecked")
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            linkLast((E)s.readObject());
    }

    @Override
    public Spliterator<E> spliterator() {
        return new LLSpliterator<E>(this, -1, 0);
    }
}

以上方法都比较简单,相对有难度的是addAll(int index, Collection<? extends E> c)方法,主要是双向链表插入元素的问题,读者可以画链表分析下,结合注释也能很容易看懂。此外,LinkedList可作为双向队列,队列和栈使用。

第4部分 LinkedList使用示例

public class Test1 {
	public static void main(String[] args) {
		LinkedList<Integer> linkedList=new LinkedList<>();
		linkedList.add(1);//[1]
		linkedList.addFirst(2);//[2,1]
		linkedList.addLast(3);//[2,1,3]
		linkedList.addAll(1, Arrays.asList(4,5,6));//[2,4,5,6,1,3]
		List<Integer>list=linkedList.subList(1, 4);//[4,5,6]
		linkedList.push(7);//[7,2,4,5,6,1,3]
	}
}

LinkedList的使用比较简单,但是方法比较多,就不都例举了。但是注意subList返回的类型为List,强制类型转换会出现类型转换异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值