Java HashSet

HashSet 的去重原理、常用方法与遍历顺序。

Beginner
Key PointsHashSet 无序、不重复,基于 HashMap 实现;判断重复靠 hashCode + equals,自定义类必须同时重写。

创建与添加

add(e) inserts and returns false for duplicates. HashSet guarantees no order: iteration does not follow insertion. Use LinkedHashSet or TreeSet when order matters.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetAdd {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();

        System.out.println(set.add("a"));
        System.out.println(set.add("a"));
        System.out.println(set.add("b"));

        System.out.println(set.size());
        System.out.println(set.contains("a"));
        System.out.println(set.contains("z"));
    }
}
Output
true
false
true
2
true
false

删除与遍历

remove(Object) deletes by value and clear() empties it. Iterate with for-each or forEach. For ordered output wrap in a TreeSet or sort afterwards.

Java
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class HashSetIter {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>(Set.of("b", "a", "c"));

        set.remove("b");
        System.out.println(set.size());

        System.out.println(new TreeSet<>(set));

        set.clear();
        System.out.println(set.isEmpty());
    }
}
Output
2
[a, c]
true

HashSet 常用方法

Beyond add, remove, contains, size, isEmpty and clear, set algebra is available: addAll for union, retainAll for intersection, removeAll for difference.

Java
import java.util.HashSet;
import java.util.Set;

public class HashSetOps {
    public static void main(String[] args) {
        Set<Integer> a = new HashSet<>(Set.of(1, 2, 3));
        Set<Integer> b = new HashSet<>(Set.of(2, 3, 4));

        Set<Integer> union = new HashSet<>(a);
        union.addAll(b);
        System.out.println(union.size());

        Set<Integer> inter = new HashSet<>(a);
        inter.retainAll(b);
        System.out.println(inter);

        Set<Integer> diff = new HashSet<>(a);
        diff.removeAll(b);
        System.out.println(diff);
    }
}
Output
4
[2, 3]
[1]
Custom objects in a HashSet must override both equals and hashCode on the same fields. Overriding only one breaks deduplication — the most common collection bug.

Friends & Partners