java 集合交並補,java集合

來源:互聯網
上載者:User

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();把你的所以集合元素添加到此集合。去除重複。
差,請你解釋下。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.