LinkedList源码解析

【1】JDK1.7和JDK1.8的LinkedList的源码是一致的

【2】

复制代码
public class LinkedList<E>{
    //E是一个泛型,具体的类型要在实例化的时候确定
    transient int size = 0;//集合中元素的数量
    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;
        }
    }
    transient Node<E> first;//链表的首节点

    transient Node<E> last;//链表的尾结点
    //空构造器
    public LinkedList() {
        
    }
    //添加元素操作
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    void linkLast(E e) {//添加的元素e
        final Node<E> l = last;//将链表中的Last节点给1如果是第一个元素的话1位null
        //将元素封装为一个Node具体的对象
        final Node<E> newNode = new Node<>(l, e, null);
        //将链表的last节点指向新的创建的对象
        last = newNode;
        if (l == null)//如果添加的是第一个节点
            first = newNode;//将链表的first节点指向新节点
        else
            l.next = newNode;//将l的下一个指向为新的节点
        size++;//集合中元素的数量加一操作
        modCount++;
    }
    //获取集合中元素的数量
    public int size() {
        return size;
    }
    //通过索引得到元素
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    Node<E> node(int index) {
        // 如果index在链表的前半段,那么从前往后找

        if (index < (size >> 1)) {
            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;
        }
    }
}
复制代码

 

posted @   爱的加勒比  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示