You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LinkedList按ID删除对象遇问题:输入ID误删索引对应元素

问题根源

你调用的LinkedList.remove(int)方法是按索引删除元素,而非按对象的ID字段匹配删除。所以输入ID=1时,它会删除列表中索引为1的元素(第二个对象),和你的需求完全不符。

解决方案

方法1:迭代器遍历删除(最安全,支持删除第一个匹配项)

System.out.println("Please enter an ID number to remove");
int targetId = scanner.nextInt();

Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
    Student student = iterator.next();
    if (student.getId() == targetId) {
        iterator.remove(); // 使用迭代器删除,避免并发修改异常
        System.out.println("删除成功");
        break; // 找到第一个匹配项后停止遍历
    }
}

注:如果需要删除所有匹配ID的对象,去掉break即可。

方法2:Java 8+ 用removeIf批量删除(最简洁)

LinkedList实现了Collection接口,直接用removeIf方法可以一键删除所有匹配ID的对象:

System.out.println("Please enter an ID number to remove");
int targetId = scanner.nextInt();

boolean isRemoved = students.removeIf(student -> student.getId() == targetId);
if (isRemoved) {
    System.out.println("删除成功");
} else {
    System.out.println("未找到对应ID的学生");
}

方法3:Stream过滤生成新列表(适合不修改原列表的场景)

如果需要保留原列表,生成一个剔除目标ID的新列表:

System.out.println("Please enter an ID number to remove");
int targetId = scanner.nextInt();

List<Student> filteredStudents = students.stream()
    .filter(student -> student.getId() != targetId)
    .collect(Collectors.toList());
// 若要替换原列表,直接赋值:students = new LinkedList<>(filteredStudents);
注意事项
  • 确保你的Student类有getId()方法,用于获取对象的ID字段。
  • 不要在普通for/增强for循环中直接调用students.remove(student),否则会触发ConcurrentModificationException。

内容的提问来源于stack exchange,提问作者NeedHelp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:55:06