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
        }
    }
}
相关推荐
Lear2 小时前
【JavaSE】反射与注解:深入剖析Java动态编程与案例实现
后端
Lear2 小时前
【JavaSE】Stream流:让集合操作变得优雅而高效
后端
IT_陈寒3 小时前
Redis性能提升50%的7个关键配置:从慢查询优化到内存碎片整理实战指南
前端·人工智能·后端
程序员岳焱3 小时前
Java 调用 DeepSeek API 的 8 个高频坑
java·人工智能·后端
汝生淮南吾在北3 小时前
SpringBoot+Vue非遗文化宣传网站
java·前端·vue.js·spring boot·后端·毕业设计·课程设计
程序员爱钓鱼3 小时前
Node.js 编程实战:自定义模块与包发布全流程解析
后端·node.js·trae
武藤一雄3 小时前
C# Prism框架详解
开发语言·后端·微软·c#·.net·wpf
程序员爱钓鱼4 小时前
Node.js 编程实战:深入理解回调函数
后端·node.js·trae
苏三说技术4 小时前
新项目为什么推荐WebFlux,而非SpringMVC?
后端