import java.util.HashSet; import java.util.Set; public class test { public static void main(String[] args) { Set<Integer> result = new HashSet<Integer>(); Set<Integer> set1 = new HashSet<Integer>(){{ add(1); add(3); add(5); }}; Set<Integer> set2 = new HashSet<Integer>(){{ add(1); add(2); add(3); }}; result.clear(); result.addAll(set1); // 将集set1所有元素加到result集合 result.retainAll(set2); // 仅保留result集合中那些包含在指定set2中的元素 System.out.println("交集:"+result); result.clear(); result.addAll(set1); result.removeAll(set2); // 移除result集合中那些包含在set2中的元素,有就删除,没有就继续删掉下一个元素 System.out.println("差集:"+result); result.clear(); result.addAll(set1); result.addAll(set2); System.out.println("并集:"+result); } }
差集:一般地,记A,B是两个集合,则所有属于A且不属于B的元素构成的集合,叫做集合A减集合B(或集合A与集合B之差),类似地,对于集合A、B,我们把集合x∣x∈A,且x∉B叫做A与B的差集
========================================Talk is cheap, show me the code=======================================