import java.util.HashSet;
import java.util.Set;
/**
*
* @author minghai
*
*/
public class TestHashSet {
public static void main(String[] args) {
Set<Integer> A = new HashSet<Integer>();
Set<Integer> B= new HashSet<Integer>();
A.add(1);A.add(2);A.add(3);A.add(4);
B.add(3);B.add(4);B.add(5);B.add(6);
System.out.println("A:"+ A);
System.out.println("B:"+ B);
// A 并 B
Set<Integer> A_B = new HashSet<Integer>();
A_B.addAll(A);
A_B.addAll(B);
System.out.println("A+B: "+A_B);
// A 交 B
Set<Integer> AB = new HashSet<Integer>();
AB.addAll(A);
AB.retainAll(B);
System.out.println("A+B: "+AB);
// B 关于 A 的补集 (由属于A而不属于B的元素组成的集合,称为B关于A的相对补集)
Set<Integer> A$B = new HashSet<Integer>();
A$B.addAll(A);
A$B.removeAll(B);
System.out.println("A+B: "+A$B);
}
}
Java集合中实现交并补
最新推荐文章于 2025-03-30 21:56:35 发布