1.List:ArrayList和LinkedList 都是有序、可重复、有索引。但是这两个底层采用的数据结构(存储、组织数据的方式)不同,适用场景不同。

List集合支持索引,有很多与索引相关的方法。

集合框架(一) List_时间复杂度

2.List支持的遍历方法

(1)for,因为有索引

(2)迭代器

(3)增强for

(4)Lambda表达式

3.ArrayList集合的底层原理

集合框架(一) List_List_02

集合框架(一) List_System_03


  • ArrayList 支持使用索引进行随机访问,时间复杂度为 O(1),这使得其在访问元素时非常高效。
  • 在末尾添加元素的时间复杂度平均为 O(1)(当没有发生扩容时)。
  • 在中间或开始位置插入或删除元素时,时间复杂度为 O(n),因为需要移动数组中的元素。

ArrayList集合适用:根据索引查询数据,比如根据随即索引取数据,或者数据量不大

不适用:数据量大同时需要频繁增删。

4.LinkedList集合的底层原理

基于双链表实现

集合框架(一) List_System_04

双链表

集合框架(一) List_时间复杂度_05

集合框架(一) List_List_06

5.LinkedList集合的应用场景

(1)设计队列,先进先出,后进后出。

(2)设计栈,先进后出push/pop

public class test {
    public static void main(String[] args) {
        // 1. 创建一个队列对象
        LinkedList<String> queue = new LinkedList<>();

        // 入队
        queue.addLast("第1颗子弹");
        queue.addLast("第2颗子弹");
        queue.addLast("第3颗子弹");
        queue.addLast("第4颗子弹");
        System.out.println(queue);

        // 出队
        System.out.println(queue.removeFirst());
        System.out.println(queue.removeFirst());
        System.out.println(queue.removeFirst());
        System.out.println(queue);
        System.out.println("------------------------------------------------");

        // 2. 创建一个栈对象
        LinkedList<String> stack = new LinkedList<>();

        // 压栈
        stack.push("第1颗子弹");
        stack.push("第2颗子弹");
        stack.addFirst("第3颗子弹");
        stack.addFirst("第4颗子弹");
        System.out.println(stack);

        // 出栈
        System.out.println(stack.pop());
        System.out.println(stack.removeFirst());
        System.out.println(stack);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.

上面可以改成push/pop操作

集合框架(一) List_List_07