ArrayList容器类

ArrayList是List接口的实现类,是List存储特征的具体实现。底层使用数组实现的存储。底层基于可边长的Object数组。

1. 核心特性

  • 有序:元素按插入顺序存储

  • 允许null: 可以添加null值

  • 非线程安全:多线程环境下,需要手动同步

  • 随机访问快:通过索引访问时间复杂度为 O(1)

  • 增删慢:在中间插入/删除需移动元素,平均时间复杂度 O(n)

  • 当容量不足时,自动扩容(默认增长 50%)

2. 增加元素实例

csharp 复制代码
import java.util.ArrayList;
import java.util.List;

public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        System.out.println(flag1);
        boolean flag2 = list.add("world");
        System.out.println(flag2);
        list.add(1, "and");
        System.out.println(list);
        list.add(5, "and"); // 报错,不可以超过数组的元素个数
        System.out.println(list);
    }
}

3. 获取元素(get)

E get(int index) // 获取指定位置的元素,如果索引超出范围(index < 0 || index >= size()),则报异常IndexOutOfBoundsException

get方法是List接口定义的方法;

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]
        System.out.println(list.get(0)); // hello
        System.out.println(list.get(1)); // and
        System.out.println(list.get(2)); // world
        System.out.println(list.get(9)); // IndexOutOfBoundsException  报错
        
        // 也可以使用for循环
        for (int i = 0; i < list.size(); i++) {
          System.out.println(list.get(i));
        }
    }
}

4. 删除元素

4.1 remove 根据索引删除元素

E remove(index) 是List接口中定义的;

这个列表中删除指定位置的元素(可选操作),范围结果是原位置的元素

注意:index超出范围会报异常;

java 复制代码
import java.util.ArrayList;
import java.util.List;

public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]

        String value = list.remove(1); // 删除位置1的元素and
        System.out.println(value); // and
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i)); // hello world
        }
    }
}

4.2 删除指定元素

boolean remove(object o) 删除指定元素,第一个匹配的元素

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]

        boolean flag = list.remove("and"); // 删除元素and
        System.out.println(flag); // true
        boolean flag = list.remove("hahaha"); // 删除hahaha
        System.out.println(flag); // false
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i)); // hello world
        }
    }
}

只删除第一个匹配的元素,如下删除and

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "and", "world"]

        boolean flag = list.remove("and"); // 删除第一个and
        System.out.println(flag); // true
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i)); // hello and world
        }
    }
}

5. 替换元素

E set(index, value); // 取代index位置上的元素,返回旧的值;

注意:可能会报的异常:

  • IndexOutOfBoundsException index超出范围
  • NullPointerException(仅当元素类型不允许 null 时)
  • UnsupportedOperationException 如果你使用的是通过 Collections.unmodifiableList() 等方法包装的不可变列表 ,调用 set 会抛此异常
csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]

        String value = list.set(1, "is");
        System.out.println(value); // and
        System.out.println(list); // hello is world
    }
}

6. 清空容器

void clear(); // 清空元素,无返回值,是Collection中定义的方法

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]

        list.clear();
        System.out.println(list); // []
    }
}

7. 判断容器是否为空

boolean isEmpty() // 返回true,如果该列表不包含元素

typescript 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]

        list.clear();

        boolean isEmpty = list.isEmpty();
        System.out.println(isEmpty); // true
    }
}

8. 判断容器中是否包含指定元素

boolean contains(object o) // 如果包含指定元素,则返回true

ini 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "world"]
        boolean flag3 = list.contains("and");
        boolean flag4 = list.contains("game");
        System.out.println(flag3); // true
        System.out.println(flag4); // false
    }
}

9.查找元素的位置

int indexOf(object o) // 第一次出现的位置 int lastIndexOf(object o) // 最后一次出现的位置

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        list.add(1, "and");
        System.out.println(list); // ["hello", "and", "and", world"]
        int index = list.indexOf("and");
        int lastIndex = list.lastIndexOf("and");
        System.out.println(index); // 1
        System.out.println(lastIndex); // 2
    }
}

10. 将单元素集合转换为数组

10.1 转换为Object数组

Object[] toArray()

将集合转换为 Object 数组 | 返回的数组是新创建的,修改数组不影响原集合。

typescript 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 实例化ArrayList容器
        List<String> list = new ArrayList<>();
        // 添加元素
        boolean flag1 = list.add("hello");
        boolean flag2 = list.add("world");
        list.add(1, "and");
        System.out.println(list);  // ["hello", "and", "world"]
        Object[] arr = list.toArray();
        System.out.println(Arrays.toString(arr)); // ["hello", "and", "world"]
    }
}

10.2 转换为泛型类型数组

<T> T[] toArray(T[] a) // 转为指定类型的数组

vbnet 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        // 集合
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");

        Object[] arr = list.toArray(); // 转换为Object[]数组 ["a", "b", "c"]
        // 不可以将转换的数组做强制类型转换
        // String[] arr = (String[]) list.toArray(); // 报错,不可以强制类型转换 Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
        at com.array.list.ArrayListTest.main(ArrayListTest.java:17)
        System.out.println("----------------");

        // 可以将集合转换为指定类型数组
        // 但是类型需要参考泛型中的类型
        String[] arr1 = list.toArray(new String[list.size()]);  // 将单元素集合转换为指定类型的数组
        System.out.println(Arrays.toString(arr1)); // ["a", "b", "c"]
    }
}

11. 容器的并集操作

boolean addAll(Collection<? extends E> c) // 添加整个集合到尾部 ,Collection就有的抽象方法

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");

        List<String> b = new ArrayList<>();
        b.add("d");
        b.add("e");
        b.add("f");

        boolean flag = a.addAll(b); // a 与b 合并
        System.out.println(flag); // true
        for(String str: a) {
            System.out.println(str); // a b c d e f
        }
    }
}

注意:如果b是空的,没有元素,则不可以并集成功

typescript 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");

        List<String> b = new ArrayList<>();

        boolean flag = a.addAll(b); // a 与b 合并
        System.out.println(flag);
        for(String str: a) {
            System.out.println(str); // a b c d e f
        }
    }
}

12. 容器的交集操作

boolean retainAll(Collection<?> c) // 仅保留 c 中包含的元素(求交集)

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");

        List<String> b = new ArrayList<>();
        b.add("b");
        b.add("c");
        b.add("d");
        boolean flag = a.retainAll(b); // 取a、b的交集
        System.out.println(flag); // true
        for(String str: a) {
            System.out.println(str); // b c
        }
    }
}

13. 容器的差集

boolean removeAll(Collection<?> c) // 删除所有与 c 中相同的元素

csharp 复制代码
public class ArrayListTest {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");

        List<String> b = new ArrayList<>();
        b.add("b");
        b.add("c");
        b.add("d");
        boolean flag = a.removeAll(b); // 取a中b不存在的元素
        System.out.println(flag); // true
        for(String str: a) {
            System.out.println(str); // a
        }
    }
}
相关推荐
止语Lab27 分钟前
好的 DX 不等于少写代码——三种语言的摩擦力设计课
后端
吃饱了得干活27 分钟前
别再手动解析 LLM 输出了!LangChain 四种结构化输出方案对比
后端·python·langchain
程序员天天困32 分钟前
Arthas trace 命令怎么用?一行定位最慢那行代码
jvm·后端
Huiturn32 分钟前
GPT 5.6 连续编码 10 小时,纯 Python 啃下 Word 二进制格式——doc2docx 实现拆解
后端
用户2986985301439 分钟前
Python 实现 Excel 与 Markdown 互转的实用指南
后端·python·excel
用户772831049084041 分钟前
krono-job:零侵入、单二进制交付的分布式任务调度平台(开源)
后端
Conan在掘金1 小时前
鸿蒙报错速查:Function lacks ending return statement,返回路径漏 return 就炸,根因 + 真解法
后端
人间凡尔赛1 小时前
AI-Native 云原生架构:2026 年从容器编排到智能体编排的范式革命
后端·云原生·架构
IT_陈寒2 小时前
Vue的响应式让我加班到凌晨3点,原来问题出在这
前端·人工智能·后端
卷无止境2 小时前
提升 Python 代码健壮性的方法大盘点
后端·python