代表了数学意义的集合概念,提供集合的并集,差集和交集运算方法:
boolean addAll(Collection<?> c) 并集运算
boolean retainAll (Collection<?> c) 交集运算
boolean removeAll(Collection<?> c) 差集运算
示例:
示例1: public class Test { public static void main(String[] args) { HashSet<String> hsa=new HashSet<String>(); hsa.add("宋江"); hsa.add("吴用"); hsa.add("武松"); hsa.add("燕子"); System.out.println("集合A原元素有:"); for(String str:hsa){ System.out.print(str+" "); } System.out.println(); HashSet<String> hsb=new HashSet<String>(); hsb.add("林黛玉"); hsb.add("贾宝玉"); hsb.add("薜宝钗"); hsb.add("宋江"); System.out.println("集合B原元素有:"); for(String str:hsb){ System.out.print(str+" "); } System.out.println(); System.out.println("集合A和B并集运算后:"); hsa.addAll(hsb); for(String str:hsa){ System.out.print(str+" "); } System.out.println(); } } | | |
示例2: public class Test { public static void main(String[] args) { HashSet<String> hsa=new HashSet<String>(); hsa.add("宋江"); hsa.add("吴用"); hsa.add("武松"); hsa.add("燕子"); System.out.println("集合A原元素有:"); for(String str:hsa){ System.out.print(str+" "); } System.out.println(); HashSet<String> hsb=new HashSet<String>(); hsb.add("林黛玉"); hsb.add("贾宝玉"); hsb.add("薜宝钗"); hsb.add("宋江"); System.out.println("集合B原元素有:"); for(String str:hsb){ System.out.print(str+" "); } System.out.println(); System.out.println("集合A和B交集运算后:"); hsa.retainAll(hsb); for(String str:hsa){ System.out.print(str+" "); } System.out.println(); } } | | |
示例3: public class Test { public static void main(String[] args) { HashSet<String> hsa=new HashSet<String>(); hsa.add("宋江"); hsa.add("吴用"); hsa.add("武松"); hsa.add("燕子"); System.out.println("集合A原元素有:"); for(String str:hsa){ System.out.print(str+" "); } System.out.println(); HashSet<String> hsb=new HashSet<String>(); hsb.add("林黛玉"); hsb.add("贾宝玉"); hsb.add("薜宝钗"); hsb.add("宋江"); System.out.println("集合B原元素有:"); for(String str:hsb){ System.out.print(str+" "); } System.out.println(); System.out.println("集合A和差集运算后:"); hsa.removeAll(hsb); for(String str:hsa){ System.out.print(str+" "); } System.out.println(); } } | | |