Java ArrayList 使用案例
ArrayList 是 Java 中最常用的动态数组实现,以下通过完整案例演示其核心用法。

基础案例:学生管理系统
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StudentManager {
public static void main(String[] args) {
// 1. 创建ArrayList
List<String> students = new ArrayList<>();
// 2. 添加元素
students.add("张三"); // 添加到末尾
students.add("李四");
students.add("王五");
students.add(1, "赵六"); // 在指定位置插入
System.out.println("学生列表: " + students);
// 3. 获取元素
String firstStudent = students.get(0);
System.out.println("第一个学生: " + firstStudent);
// 4. 修改元素
students.set(2, "钱七");
// 5. 删除元素
students.remove("赵六"); // 按对象删除
students.remove(0); // 按索引删除
// 6. 遍历元素 - 多种方式
System.out.println("\n遍历方式1 - for循环:");
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
System.out.println("遍历方式2 - 增强for循环:");
for (String student : students) {
System.out.println(student);
}
System.out.println("遍历方式3 - Iterator:");
Iterator<String> it = students.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// 7. 常用方法
System.out.println("\n是否为空: " + students.isEmpty());
System.out.println("学生数量: " + students.size());
System.out.println("是否包含王五: " + students.contains("王五"));
// 8. 清空列表
students.clear();
System.out.println("清空后人数: " + students.size());
}
}
进阶案例:商品库存管理
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Product {
private String name;
private double price;
private int stock;
public Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
// getter方法
public String getName() { return name; }
public double getPrice() { return price; }
public int getStock() { return stock; }
@Override
public String toString() {
return String.format("商品: %s, 价格: %.2f, 库存: %d", name, price, stock);
}
public static void main(String[] args) {
// 创建商品列表
ArrayList<Product> products = new ArrayList<>();
// 添加商品
products.add(new Product("苹果", 5.5, 100));
products.add(new Product("香蕉", 3.2, 50));
products.add(new Product("西瓜", 8.8, 30));
products.add(new Product("葡萄", 12.5, 80));
System.out.println("=== 原始商品列表 ===");
products.forEach(System.out::println);
// 按价格排序
Collections.sort(products, (p1, p2) ->
Double.compare(p1.getPrice(), p2.getPrice()));
System.out.println("\n=== 按价格排序后 ===");
products.forEach(System.out::println);
// 过滤出库存大于50的商品
ArrayList<Product> filterProducts = new ArrayList<>();
for (Product p : products) {
if (p.getStock() > 50) {
filterProducts.add(p);
}
}
System.out.println("\n=== 库存大于50的商品 ===");
filterProducts.forEach(System.out::println);
// 批量添加
ArrayList<Product> newProducts = new ArrayList<>();
newProducts.add(new Product("橙子", 4.5, 60));
newProducts.add(new Product("草莓", 25.0, 20));
products.addAll(newProducts);
System.out.println("\n=== 添加新商品后 ===");
products.forEach(System.out::println);
// 转换为数组
Product[] productArray = products.toArray(new Product[0]);
System.out.println("\n数组长度: " + productArray.length);
// 线程安全转换
// List<Product> safeList = Collections.synchronizedList(products);
}
}
实用技巧案例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayListUtils {
public static void main(String[] args) {
// 1. 初始化ArrayList的多种方式
// 方式1: 创建空列表
List<String> list1 = new ArrayList<>();
// 方式2: 指定初始容量
List<String> list2 = new ArrayList<>(20);
// 方式3: 从其他集合创建
List<String> list3 = new ArrayList<>(Arrays.asList("A", "B", "C"));
// 方式4: 使用匿名内部类(不推荐生产使用)
List<String> list4 = new ArrayList<>() {{
add("X");
add("Y");
add("Z");
}};
// 2. 高效的批量操作
List<Integer> numbers = new ArrayList<>();
// 批量添加
numbers.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
// 批量删除
numbers.removeAll(Arrays.asList(1, 3, 5));
System.out.println("删除后: " + numbers);
// 保留指定元素
numbers.retainAll(Arrays.asList(2, 4, 6));
System.out.println("保留后: " + numbers);
// 3. 处理基本类型
// ArrayList不能存储基本类型,需要使用包装类
ArrayList<Integer> integerList = new ArrayList<>();
integerList.add(10); // 自动装箱
integerList.add(20);
int val = integerList.get(0); // 自动拆箱
// 4. 查找操作
ArrayList<String> fruits = new ArrayList<>(
Arrays.asList("Apple", "Banana", "Orange", "Apple")
);
// 查找元素索引
int firstIndex = fruits.indexOf("Apple");
int lastIndex = fruits.lastIndexOf("Apple");
System.out.println("Apple第一次出现: " + firstIndex);
System.out.println("Apple最后一次出现: " + lastIndex);
// 5. 子列表操作
List<String> subList = fruits.subList(1, 3);
System.out.println("子列表: " + subList);
// 注意:subList返回的是视图,修改会影响原列表
subList.add("Grape");
System.out.println("原列表也被修改: " + fruits);
// 6. 性能优化 - 设置初始容量
ArrayList<Integer> optimized = new ArrayList<>(1000000);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
optimized.add(i);
}
long end = System.currentTimeMillis();
System.out.println("设置容量耗时: " + (end - start) + "ms");
// 无初始容量对比
ArrayList<Integer> notOptimized = new ArrayList<>();
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
notOptimized.add(i);
}
end = System.currentTimeMillis();
System.out.println("无容量设置耗时: " + (end - start) + "ms");
}
}
注意事项
-
线程安全:ArrayList 不是线程安全的,多线程环境需要使用
Collections.synchronizedList()或CopyOnWriteArrayList -
性能考虑:
- 频繁增删元素时,考虑使用
LinkedList - 频繁随机访问时,ArrayList 性能更好
- 可以预估大小时,指定初始容量避免频繁扩容
- 频繁增删元素时,考虑使用
-
遍历时删除:
// 错误方式:会抛出 ConcurrentModificationException for (String s : list) { if (s.equals("delete")) { list.remove(s); } }
// 正确方式1:使用Iterator
Iterator
// 正确方式2:使用removeIf list.removeIf(s -> s.equals("delete"));
ArrayList 是 Java 开发中最常用的集合之一,掌握这些案例可以应对大部分日常开发场景。