java 集合交並補,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 supersetpublic 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 intersectionpublic static <T> Set<T> complement(Set<T>s1,Set<T> s2){return difference(union(s1,s2),intersection(s1,s2));}}
用一個參數的JAVA程式實現集合的交並差運算
import java.util.HashSet;
import java.util.Iterator;
public class Testcase {
int x1[], x2[];
Testcase(int a[], int b[]) {
x1=a;
x2=b;
}
Testcase(Testcase d) {
x1=d.x1;
x2=d.x2;
}
public void Jiaoji(Testcase a) {
for(int i=0; i < a.x1.length; i++){
for(int j=0; j < a.x2.length; j++){
if(a.x1[i] == a.x2[j])
System.out.print(a.x1[i] + ",");
}
}
}
public static void main(String[] args) {
int x1[]= {
1, 4, 6, 9, 12, 18, 19, 45
};
int x2[]= {
4, 7, 9, 13, 19, 23, 29, 67
};
Testcase b=new Testcase(x1, x2);
b.Jiaoji(b);
System.out.println("並集是;");
int union[]=union(x1, x2);
for(int i:union){
System.out.print(i+" ");
}
System.out.print("\n差集是: ");
int diff[]=difference(x1, x2);
for(int i:diff){
System.out.print(i+" ");
}
}
//並集
static public int[] union(int a[], int b[]) {
HashSet<Integer> set=new HashSet<Integer>();
for(int i:a){
set.add(new Integer(i));
}
for(int i:b){
set.add(new Integer(i));
}
int size=set.size();
int out[]=new int[size];
Iterator<Integer> iter=set.iterator();
for(int i=0;i<size;i++){
//
//while(i.hasNext()){
out[i]=((Integer)iter.next()).intValue();
}
return out;
}
//差集
static public int[] difference(int a[], int b[]) {
HashSet<Integer> set=new HashSet<Integer>();
for(int i:a){
set.add(new Integer......餘下全文>>
java解決多個集合的交,並,差運算,做成介面,急,盼望的協助
這個只提供思路,不提供代碼。
這個就算JS都能搞定的。
先寫一個方法,去除集合中的重複 chongfu(list)
交:聲明一個list集合。使用addAll();把你的所以集合元素添加到此集合。使用list的contains方法判斷是否重的,如果重的添加帶一個新集合中,然後取出 重複
並:聲明一個list集合。使用addAll();把你的所以集合元素添加到此集合。去除重複。
差,請你解釋下。