LinkedList

继承关系

Arraylist是以数组实现集合,而LinkedList是以双向链表实现的集合,LinkedList的继承关系如下:
在这里插入图片描述
Linkedlist与Arraylist的区别有:
1.Arraylist直接继承AbstractList,而Linkedlist是继承的AbstractSequentialList
2.Arraylist实现了RandomAccess接口可以直接用foreach遍历,而LinkedList没有实现,因此不能foreach遍历
3.LinedList实现Deque(双向队列接口)

属性

LinkedList的属性主要如下,包含
Node:first 头指针
Node:last 尾指针
size linkedlist长度

	transient int size = 0;

    /**
     * Pointer to first node.
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     */
    transient Node<E> last;

其中Node对象是LinkedList的内部类,是一个双向链表

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(Collection<? extends E> c)

	public LinkedList(Collection<? extends E> c) {
		//先调用无参构造方法
        this();
        //然后将结合对象添加到链表
        addAll(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遍历到index+1,从succ.prev开始插入,最后prev.next = succ
            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)
            	//pred为空表示空链表,直接头指针指向newNode
                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;
    }

常用方法

add方法

add(E e)
直接插入到链表尾部

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

add(int index, E element)
指定位置插入,根据index的位置不同分为直接尾节点插入和找到index节点,然后将index.prev的next换成新插入的值,新插入的值的next换成找到的index节点

	public void add(int index, E element) {
		//检查是否越界
        checkPositionIndex(index);

        if (index == size)
        	//index==size直接尾部插入
            linkLast(element);
        else
        	//找到index前一个结点插入 linkBefore(E e, Node<E> succ)
            linkBefore(element, node(index));
    }

addFirst(E e)
直接头部插入,first换成新节点,新节点的next是之前的first

	public void addFirst(E e) {
        linkFirst(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++;
    }

addLast(E e)
直接调用尾部插入linkLast(e);

	public void addLast(E e) {
        linkLast(e);
    }

Remove方法

remove() 默认删除头节点

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; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }
调用
调用
remove
removeFirst
unlinkFirst

remove(int index) 删除指定index位置

 	public E remove(int index) {
        //判断是否越界,主要因为非线程安全
        checkElementIndex(index);
        //向unlink方法传入index的节点,然后让index.prev指向index.next
        return unlink(node(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;
        } 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(index)
checkElementIndex 检查是否越界
unlink

remove(Object o)删除第一个与O值相同的节点,如果O为null就删除第一为null的节点,可以说明插入的时候支持null

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;
    }
检查
为null
不为null
remove (o)
o是否为null
删除第一个null节点
删除第一个o值的节点

Get方法

get(int index)返回node(inde).item值

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
调用
调用
get index
checkElementIndex 检查是否越界
node(index).item

getFirst()头节点不为空直接返回头节点值

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

getLast()尾节点不为空直接返回尾节点值

public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

Iterator

LinekedList调用的是父类AbstractSequentialList的iterator方法
在这里插入图片描述

public Iterator<E> iterator() {
        return listIterator();
    }
    //Arraylist复写的listIterator
public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

LinkedList返回的是复写的ListItr迭代器

ListItr

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;
            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();
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LinkedListJava中的一个类,它实现了List接口和Deque接口,可以被看作是一个顺序容器、队列和栈。LinkedList的遍历过程和查找过程类似,可以从头节点开始往后遍历。然而,LinkedList不擅长随机位置访问,如果使用随机访问遍历LinkedList,效率会很低。通常情况下,我们会使用foreach循环来遍历LinkedList,因为foreach最终会转换成迭代器形式。LinkedList的遍历核心就是它的迭代器实现。[1] LinkedList的继承体系较为复杂,它继承自AbstractSequentialList类,并实现了List和Deque接口。AbstractSequentialList是一个基于顺序访问的接口,通过继承此类,子类只需实现部分代码即可拥有完整的一套访问某种序列表的接口。LinkedList还实现了Deque接口,Deque又继承自Queue接口,因此LinkedList具备了队列的功能。[2][3] LinkedList的实现方式决定了所有与下标有关的操作都是线性时间复杂度,而在首段或末尾删除元素只需要常数时间复杂度。LinkedList没有实现同步(synchronized),如果需要多个线程并发访问,可以使用Collections.synchronizedList()方法对其进行包装。[2] 总结来说,LinkedList是一个灵活的数据结构,可以用作顺序容器、队列和栈。它的遍历过程需要注意效率问题,不适合随机位置访问。LinkedList的继承体系较为复杂,继承自AbstractSequentialList类,并实现了List和Deque接口。LinkedList的实现方式决定了与下标有关的操作是线性时间复杂度,而在首段或末尾删除元素只需要常数时间复杂度。[1][2][3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值