ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

集合之linkedList源码解析

2021-05-16 17:36:33  阅读:123  来源: 互联网

标签:Node index 解析 return linkedList next 源码 null first


类图:

 

 LinkedList 是基于节点实现的双向链表的 List ,每个节点都指向前一个和后一个节点从而形成链表。

实现接口:相比ArrayList 少了RandomAcess 多了Deque

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;

通过 Node 节点指向前后节点,从而形成双向链表。
first 和 last 属性:链表的头尾指针。
在初始时候,first 和 last 指向 null ,因为此时暂时没有 Node 节点。
在添加完首个节点后,创建对应的 Node 节点 node1 ,前后指向 null 。此时,first 和 last 指向该 Node 节点。
继续添加一个节点后,创建对应的 Node 节点 node2 ,其 prev = node1 和 next = null ,而 node1 的 prev = null 和 next = node2 。此时,first 保持不变,指向 node1 ,last 发生改变,指向 node2 。
size 属性:链表的节点数量。通过它进行计数,避免每次需要 List 大小时,需要从头到尾的遍历。

构造方法:

  public LinkedList() {
    }


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

新增add: 相比ArrayList 不需要考虑扩容

 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;
        //如果末尾last 元素为null 表示这个列表为null  就放在first
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        //增加数组修改次数
        modCount++;
    }

指定位置新增:add(int index, E element)

 public void add(int index, E element) {
       //检查下标位置范围
        checkPositionIndex(index);
       //如果插入位置和size 相等 则放在最后一位
        if (index == size)
            linkLast(element);
        else
        //else 则放在指定位置
            linkBefore(element, node(index));
    }
    
    Node<E> node(int index) {
        // assert isElementIndex(index);
        //如果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;
        }
    }
    
    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++;
    }

添加到列表头部:addFirst

   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

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

添加集合addAll:

 public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
public boolean addAll(int index, Collection<? extends E> c) {
        //检查下标位置范围
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        //新增集合长度为0 返回false 
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        //如果添加位置和原列表长度相等 ,则将last 赋值为pred 
        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;
    }

移除元素:remove()  默认移除首个元素

public E remove() {
        return removeFirst();
    }
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}

移除指定元素:remove (object 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;
    }

移除指定位置元素:remove(int index) 

   public E remove(int index) {
        //检查元素下标位置
        checkElementIndex(index);
        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;
         // prev 为null 表示 该节点为首节点 移除后将该节点的next节点赋值为fisrt
        if (prev == null) {
            first = next;
        } else {
        //该元素的前一个元素的next 指向该元素的下一个节点next 
            prev.next = next;
            x.prev = null;
        }
        //next 为null 表示该节点为末尾 则移除该元素后该元素的前一个节点就为最后一个节点了
        if (next == null) {
            last = prev;
        } else {
        //该元素的下一个元素的头部指向该元素的前一个元素
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }

获取元素下标:

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

判断是否包含某个元素:catains

 public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

获取指定元素:get(int index)

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

设置指定位置元素:set(int index, E element)

public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

因为 LinkedList 实现了 Queue 接口,所以它实现了 #peek() 和 #peek() 和 #element() 方法,分别获得元素到链表的头。

public E peek() {
    final Node<E> f = first;
    return (f == null) ? null : f.item;
}

public E element() { // 如果链表为空识,抛出 NoSuchElementException 异常
    return getFirst();
}
public E getFirst() {
    final Node<E> f = first;
    if (f == null) // 如果链表为空识,抛出 NoSuchElementException 异常
        throw new NoSuchElementException();
    return f.item;
}

转化为为数组:toArray()  返回值为Object数组  实际开发中我们需要转化为对应类型数组toArray(T[] a)

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

清空列表:clear

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

克隆 : 调用父方法super.clone()  ;first ,last,size,modCount 是 重新初始化进来,不与原 LinkedList 共享

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

 

标签:Node,index,解析,return,linkedList,next,源码,null,first
来源: https://www.cnblogs.com/wlong-blog/p/14774231.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有