java 集合交并补

通过使用泛型方法和Set来表达数学中的表达式:集合的交并补。在下面三个方法中都将第一个參数Set复制了一份,并未直接改动參数中Set。
package Set;

import java.util.HashSet;
import java.util.Set;

public class Sets {
	public  static <T> Set<T> intersection(Set<T> s1, Set<T> s2) {
		Set<T> result = new HashSet<T>(s1);
		result.retainAll(s2);
		return result;
	}

	public  static <T> Set<T> union(Set<T> s1, Set<T> s2) {
		Set<T> result = new HashSet<T>(s1);
		result.addAll(s2);
		return result;
	}
	
	//Subtract subset from superset
	public  static <T> Set<T> difference (Set<T> superset, Set<T> subset) {
		Set<T> result = new HashSet<T>(superset);
		result.addAll(subset);
		return result;
	}
	
	//Reflexive --everything not in their intersection
	public static <T> Set<T> complement(Set<T>s1,Set<T> s2){
		return difference(union(s1,s2),intersection(s1,s2));
	}
}

posted @ 2017-06-05 20:30  wzzkaifa  阅读(901)  评论(0编辑  收藏  举报