一个实用的Set例子
public class Sets{
public static <T> Set<T> union<Set<T> a ,Set<T> b){
Set<T> result = new HashSet<T>(a);
result.addAll(b);
return result;
}
public static <T> Set<T> intersection(Set<T> a,Set<T> b){
Set<T> result = new HashSet<T>(a);
result.retailAll(b);
return result;
}
public static <T> Set<T> difference(Set<T> a ,Set<T> b){
Set<T> result = new hashSet<T>(a);
result.removeAll(b);
return result;
}
public static <T> Set<T> complement(Set<T> a, Set<T> b){
return difference(union(a,b),intersection(a,b));
}
}
前三种方法中,都是将第一个参数Set复制一份,将Set中的所有引用都存入一个新的HashSet对象中,因此我们并没有修改参数中的Set,返回的值是一个全新的Set对象。
union返回一个Set,它将俩个参数合并一起,interseciton返回的Set只包含俩个参数共同的部分,difference方法从a中包含b的元素,complement方法返回set包含除了交集之外的元素。