文章目录

  • 前言
  • 一、LinkedList
  • 二、使用
  • 1.构造器
  • 2.常用方法
  • 2.1 添加 + 获取 + 移除
  • 2.2 获取元素个数
  • 2.3 是否为空
  • 2.4 是否包含
  • 最后
  • 相关





前言

LinkedList 链表,链表是一种非连续、非顺序的存储结构。插入快,查询慢。

LinkedList 实现了Queue 和 Deque 接口,可以作为队列或者双端队列来用。

LinkedList 是线程不安全的。

一、LinkedList

List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。
此类实现 Deque 接口,为 add、poll 提供先进先出队列操作,以及其他堆栈和双端队列操作。
所有操作都是按照双重链接列表的需要执行的。在列表中编索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端)。

java LinkedList能设置长度吗 java linkedlist方法_双端队列

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable

二、使用

1.构造器

创建一个空链表

LinkedList<Integer> list = new LinkedList<>();

2.常用方法

2.1 添加 + 获取 + 移除

add(E e) 将指定元素添加到此列表的结尾。
add(int index, E element) 在此列表中指定的位置插入指定的元素。
get(int index) 返回此列表中指定位置处的元素。
getFirst() 返回此列表的第一个元素。
getLast() 返回此列表的最后一个元素。
remove(int index) 移除此列表中指定位置处的元素。
remove() 获取并移除此列表的头(第一个元素)。
remove(Object o) 从此列表中移除首次出现的指定元素(如果存在)。

除此之外,还有很多类似的方法,比如添加可以使用push()、获取可以使用peek()、移除看使用pop()。
更多方法推荐查看JDK API

LinkedList<String> list = new LinkedList<>();
        String str01 = "str01";
        // 添加
        list.add(str01);
        list.add("str02");
        // 添加到指定元素后
        list.add("str03");
        System.out.println(list); // [str01, str02, str03]

        // 获取指定下标的元素
        String s0 = list.get(0);
        System.out.println(s0); // str01
        // 获取第一个
        String first = list.getFirst();
        System.out.println(first); // str01
        // 获取最后一个
        String last = list.getLast();
        System.out.println(last); // str03

        // 移除并获取第一个元素
        String remove0 = list.remove(0);
        System.out.println(remove0); // str01
        String remove = list.remove();
        System.out.println(remove); // str02
        boolean str03 = list.remove("str03"); // 移除链表中的str03
        System.out.println(str03); // true
    
        // 空链表,因为都移除了
        System.out.println(list);
2.2 获取元素个数

size()
返回此列表的元素数。

LinkedList<String> list = new LinkedList<>();
        list.add("str01");
        list.add("str02");
        list.add("str03");

        // 获取元素个数
        int size = list.size();
        System.out.println(size); // 3
2.3 是否为空

这是从父类 AbstractCollection类继承来的方法。

LinkedList<String> list = new LinkedList<>();
        boolean empty = list.isEmpty();
        System.out.println(empty); // true
2.4 是否包含

contains(Object o)
如果此 collection 包含指定的元素,则返回 true。

LinkedList<String> list = new LinkedList<>();
        list.add("str01");
        boolean contains = list.contains("str01");
        System.out.println(contains); // true



最后

LinkedList 的其他方法和 ArrayList 的常用方法使用基本差不多。其他的相信你看一眼JDK API也能秒懂的。

不过链表数据结构的方法比较特别的,不过也是见名知意的。



相关

更多常用类请查看:【Java SE 常用类】目录