ArrayList
ArrayList
ArrayList
for (int i = 0; i < colors.size(); i++) {
System.out.println(colors.get(i));
}
// ArrayList在中间插入
ArrayList
// LinkedList在中间插入
LinkedList

// 没有泛型的痛苦经历 ArrayList oldList = new ArrayList(); oldList.add("hello"); oldList.add(123); // 编译通过,运行时可能出问题 String str = (String) oldList.get(1); // ClassCastException!
// 使用泛型的清爽体验
ArrayList
// 定义学生类 class Student {
private String id;
private String name;
private double score;
// 构造方法、getter/setter省略
}

// 使用ArrayList管理学生列表
ArrayList
// 添加学生 studentList.add(new Student("001", "张三", 85.5)); studentList.add(new Student("002", "李四", 92.0));
// 按学号查找学生 public Student findStudentById(String id) {
for (Student student : studentList) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
// 按成绩排序 studentList.sort((s1, s2) -> Double.compare(s2.getScore(), s1.getScore()));