• Java 源码 LinkedList 集合类


    介绍

    Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements including null.

    示例

    public class App {
      public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("费");
        list.add("哥");
        list.forEach(System.out::print);
      }
    }
    

    结构

    源码

    成员变量

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

    构造方法

    /**
     * Constructs an empty list.
     */
    public LinkedList() { }
    

    成员方法

    添加

    /**
     * Links e as last element.
     */
    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++;
    }
    

    刪除

    /**
     * Unlinks non-null node x.
     */
    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;
    }
    

    面试

    它与 ArrayList 的区别?
    1、一个是动态数组的数据结构,一个是链表的数据结构,都是对 List 接口的实现。
    2、随机访问 ArrayList 的效率高,它底层数组支持随机访问,LinkedList 需要移动指针从前往后依次查找。
    3、增删的操作 LinkedList 的效率更高,它修改一些指针的方向即可,ArrayList 需要进行数据的移动。
    如何实现 LinkedList 线程安全?
    1、使用 Collections.synchronizedList 包装一下 List,内部使用了 synchronized (mutex) 修饰方法体。
    2、使用 ConcurrentLinkedQueue 集合类,内部使用 CAS算法。

  • 相关阅读:
    webpack打包代码生成npm包和js文件学习记录
    王道每周工作记录
    20211116 nuxt项目移动端网页修复记录
    ubuntuwireshark打开出现错误的问题
    Python3基础使用RSA2(SHA256WithRSA)签名加密作为sign值的问题
    博客成长志
    OI学习日志 12月份
    docker 运行.net镜像服务运行正常但是连接不上sqlserver数据库解决方案
    国外一位Orchard的blog
    mvc 相关联的下拉列表 cascading dropdownlist
  • 原文地址:https://www.cnblogs.com/feiqiangsheng/p/16188185.html
Copyright © 2020-2023  润新知