答案是重写equals和hashCode后用Set或Stream去重。需根据业务字段重写equals和hashCode方法,再利用HashSet、LinkedHashSet或Stream的distinct实现去除自定义对象重复,注意可变字段可能引发集合行为异常。

在Java中清除集合中的重复自定义对象,关键在于正确重写 equals() 和 hashCode() 方法,并使用合适的集合类型如 HashSet 或 LinkedHashSet 来自动去重。
1. 重写 equals() 和 hashCode()
自定义对象默认使用继承自Object类的 equals() 和 hashCode(),它们基于内存地址判断是否相等,无法识别逻辑上的重复。必须根据业务字段手动重写这两个方法。
例如有一个 Student 类:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
2. 使用 Set 集合去重
Set 接口的实现类不允许重复元素,添加时会自动调用 equals() 和 hashCode() 判断是否重复。
立即学习“Java免费学习笔记(深入)”;
- 使用 HashSet:无序去重
- 使用 LinkedHashSet:保持插入顺序
示例代码:
Listlist = new ArrayList<>(); list.add(new Student("Alice", 20)); list.add(new Student("Bob", 22)); list.add(new Student("Alice", 20)); // 重复 Set set = new LinkedHashSet<>(list); List noDuplicates = new ArrayList<>(set);
3. 使用 Java 8 Stream 去重
通过 distinct() 方法也能实现去重,底层同样依赖 equals() 和 hashCode()。
ListnoDuplicates = list.stream() .distinct() .collect(Collectors.toList());
基本上就这些。只要保证 equals() 和 hashCode() 正确,去重就不难。注意:如果对象字段会变,不建议用作 HashMap 的 key 或放入 Set,否则可能引发不可预期的问题。










