Java之Set
Set是扩展Collection的接口。 它是对象的无序集合,其中不能存储重复值。
通常情况下,Set是由HashSet,LinkedHashSet或TreeSet实现的。
Set具有多种方法来添加,删除,排序等,以增强此接口的使用。
下面是一个往Set集中添加数据的例子
public class Set_example {
public static void main(String[] args) {
Set hash_Set = new HashSet();
hash_Set.add("Happy");
hash_Set.add("Day");
hash_Set.add("Happy");
hash_Set.add("Every");
hash_Set.add("Moment");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
System.out.print("Sorted Set after passing into TreeSet");
Set tree_Set = new TreeSet(hash_Set);
System.out.println(tree_Set);
}
}
输出:
Set output without the duplicates[Moment,Every,Happy,Day]
Sorted Set after passing into TreeSet[Day,Every,Happy,Moment]
我们输入了一个重复的实体,但是它没有显示在输出中。并且,我们可以通过将无序Set传入作为TreeSet的参数来直接对输入进行排序。
现在我们继续来看Set上的一些基本操作,即并集,相交和差。
public class setep {
public static void main(String args[]) {
Set a =new HashSet();
a.addAll(Arrays.asList(new Integer[] {1, 3, 2, 4, 8, 9, 0}));
Set b =new HashSet();
b.addAll(Arrays.asList(new Integer[] {1, 3, 7, 5, 4, 0, 7, 5}));
Set union =new HashSet(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
Set intersection =new HashSet(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);
Set difference =new HashSet(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}
输出:
Union of the two Set[0,1,2,3,4,5,6,7,8,9]
Intersection of the two Set[0,1,3,4]
Difference of the two Set[2,8,9]