java 的 hashset 本身不直接提供集合运算方法,但可以通过调用 addall()、removeall() 和 retainall() 来执行并集、差集和交集操作。具体做法是:将源集合复制到另一个 hashset 实例中,然后在该副本上调用上述方法,这样既能得到运算结果,又不会修改原始数据。

如何计算两个集合的并集
要计算两个集合的并集,只需创建一个包含第一个集合所有元素的副本,然后调用 addAll() 方法传入第二个集合。该方法会将第二个集合中的所有元素添加到副本中,自动处理重复项。

import java.util.HashSet;
import java.util.Set;
public class UnionExample {
public static void main(String[] args) {
Set<string> setA = new HashSet();
setA.add("Apple");
setA.add("Banana");
Set<string> setB = new HashSet();
setB.add("Banana");
setB.add("Cherry");
// 创建副本以保留原始集合
Set<string> union = new HashSet(setA);
union.addAll(setB);
System.out.println("Union: " + union);
}
}</string></string></string>
如何计算两个集合的差集
要计算集合 A 对集合 B 的差集(即 A - B),需要创建集合 A 的副本,然后调用 removeAll() 方法传入集合 B。该方法会从副本中移除所有出现在集合 B 中的元素。

import java.util.HashSet;
import java.util.Set;
public class DifferenceExample {
public static void main(String[] args) {
Set<string> setA = new HashSet();
setA.add("Apple");
setA.add("Banana");
setA.add("Cherry");
Set<string> setB = new HashSet();
setB.add("Banana");
setB.add("Date");
// 创建副本以保留原始集合
Set<string> difference = new HashSet(setA);
difference.removeAll(setB);
System.out.println("Difference (A - B): " + difference);
}
}</string></string></string>
如何处理空值输入导致的异常
在使用 HashSet 进行集合运算时,如果传入的参数为 null,会抛出 NullPointerException。这是因为 HashSet 内部依赖对象的 equals() 和 hashCode() 方法,而 null 无法调用这些方法。因此,在执行 addAll()、removeAll() 或 retainAll() 之前,必须确保传入的集合不为 null。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











