HashSet通过hashCode和equals方法实现去重,内置类型可直接使用,自定义类需重写这两个方法,如Student类按id和name去重,确保逻辑相同对象不重复添加。

在Java中,HashSet 是基于哈希表实现的集合类,它继承自 AbstractSet 并实现了 Set 接口。由于 Set 集合不允许重复元素,因此 HashSet 天然适合用于集合去重。只要正确使用,就能高效地去除重复数据。
HashSet 判断元素是否重复依赖于对象的 equals() 和 hashCode() 方法:
因此,若要让自定义对象在 HashSet 中正确去重,必须重写这两个方法。
对于 String、Integer 等 Java 内置类型,系统已重写了 hashCode 和 equals 方法,可直接用于去重。
立即学习“Java免费学习笔记(深入)”;
import java.util.*;
public class DedupExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "banana");
Set<String> uniqueSet = new HashSet<>(list);
System.out.println(uniqueSet); // 输出:[banana, orange, apple](顺序不保证)
}
}
这段代码将原始列表转为 HashSet,自动去除重复字符串,简单高效。
若想对自定义类的对象去重,比如学生信息,需确保逻辑上“相同”的对象被视为重复。
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return id == student.id && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
}
}
使用示例:
List<Student> students = Arrays.asList(
new Student(1, "Alice"),
new Student(2, "Bob"),
new Student(1, "Alice")
);
Set<Student> uniqueStudents = new HashSet<>(students);
System.out.println(uniqueStudents);
// 输出仅包含两个元素,重复的 Student(1, "Alice") 被去除
如果不重写 hashCode 和 equals,即使内容相同,也会被视为不同对象,导致去重失败。
LinkedHashSet)。Collections.synchronizedSet。基本上就这些。只要理解了 hashCode 和 equals 的作用,用 HashSet 去重非常直观。对于大多数去重场景,它是首选方案。注意自定义类务必重写关键方法,否则去重可能失效。
以上就是在Java中如何使用HashSet进行集合去重_HashSet集合实践方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号