Java集合之LinkedList

一、底层数据结构

在这里插入图片描述
ObviousLy, LinkList内部使用的是一个双向链表.

二、方法思维导图

在这里插入图片描述
And, 继承的方法就不列了.

三、部分方法的源代码

构造方法

方法一:

public LinkedList() {
    }

方法二:

public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

进入addAll ➷

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

Go on ➷

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;
    }
获取指定索引处元素
public E get(int index)

这就是 LinkedList 查询元素不及 ArrayList 的原因, LinkedList得遍历链表获取引用 (index与遍历的次数有关) , 且index越是靠近集合中间花费的时间越多.

// 关键代码
// 获取引用
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;
    }
}
移除集合第一个元素
// 关键代码
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;
    }

从源码可以看出LinkedList删除元素的方式比ArrayList快多了.
LinkedList只需要修改引用即可,
ArrayList则需要将该元素右边的引用都要左移.

// ArrayList删除元素
System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值