HashSet通过哈希表实现元素唯一性,添加元素时自动去重,适用于快速查找、去重及集合操作,但需重写自定义类的hashCode与equals方法以确保正确性。

Java中要存储唯一元素,
HashSet
HashSet
HashSet
Set
HashMap
HashSet
hashCode()
equals()
这里有个简单的例子,展示了
HashSet
import java.util.HashSet;
import java.util.Set;
public class UniqueElementsExample {
public static void main(String[] args) {
Set<String> uniqueNames = new HashSet<>();
System.out.println("尝试添加元素...");
// 添加一些字符串
System.out.println("添加 'Alice': " + uniqueNames.add("Alice")); // 第一次添加,通常返回true
System.out.println("添加 'Bob': " + uniqueNames.add("Bob"));
System.out.println("添加 'Alice' (重复): " + uniqueNames.add("Alice")); // 重复添加,返回false
System.out.println("添加 'Charlie': " + uniqueNames.add("Charlie"));
System.out.println("添加 'Bob' (重复): " + uniqueNames.add("Bob")); // 重复添加,返回false
System.out.println("\nHashSet中的唯一元素:");
for (String name : uniqueNames) {
System.out.println(name);
}
System.out.println("\nHashSet的大小: " + uniqueNames.size()); // 预期大小为3
}
}运行这段代码,你会发现输出结果中“Alice”和“Bob”只出现了一次,
HashSet
HashSet
立即学习“Java免费学习笔记(深入)”;
对于像
String
Integer
hashCode()
equals()
HashSet
HashSet
Object
hashCode()
equals()
要让
HashSet
hashCode()
equals()
equals()
true
hashCode()
hashCode()
equals()
true
equals
举个例子,假设我们有一个
Person
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// 默认情况下,HashSet会认为两个内容相同的Person对象是不同的
// 因为它们在内存中的地址不同。
// 必须重写hashCode()和equals()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
// 通常使用Objects.hash()来生成哈希码,它会综合考虑所有参与equals比较的字段
return java.util.Objects.hash(name, age);
}
}在上面的
Person
equals()
hashCode()
equals()
name
age
hashCode()
HashSet
Person
Person
Person
如果你忘记重写或者重写不当,比如只重写了
equals()
hashCode()
HashSet
HashSet
性能特点:
HashSet
HashSet
HashSet
Collections.synchronizedSet(new HashSet<>())
java.util.concurrent.ConcurrentHashMap
keySet()
HashSet
ArrayList
适用场景:
HashSet
HashSet
List<String> rawList = Arrays.asList("apple", "banana", "apple", "orange", "banana");
Set<String> uniqueItems = new HashSet<>(rawList); // 快速去重
System.out.println(uniqueItems); // 输出: [orange, banana, apple] (顺序不确定)HashSet
contains()
Set<String> dictionary = new HashSet<>(Arrays.asList("cat", "dog", "bird"));
boolean found = dictionary.contains("dog"); // O(1)查找HashSet
retainAll()
addAll()
removeAll()
总的来说,当你关注元素的唯一性,并且需要对元素进行快速的添加、删除和查找操作,同时对元素的顺序没有要求时,
HashSet
hashCode()
equals()
以上就是如何在Java中使用HashSet存储唯一元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号