java源码分析08-LinkedList

喜欢一个人,就会喜欢她的一切吗?

今天,我们来看下LinkedList的结构。



LinkedList内部其实是双向链表实现的,而且拥有轮询以及出栈的功能。

增删改查:

 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之后需要将size加一,modCount也需要加一。


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



查询的时候,需要先检查是否为有效查询,也就是下标是否在0与size-1之间。


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


此处有一个优化,首先判断下标是在中间节点的左边还是右边,如果在左边就从头结点开始遍历;否则从尾结点开始遍历查询。


轮询机制

 public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }


此处为什么定义一个final类型的引用,而没有直接unlinkFirst(first)?


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

删除头结点,第一步,提前存储头结点的后继;第二,头结点的值设为null,其下一节点为null;第三,将first指向之前存储的已删除节点的后继。第四,判断后继是否为空,为空那么last为null,否则后继的前驱为null。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值