1
我已經編寫了一個包含2個不同數字集合的程序,我想知道如何從這兩個集合中獲得聯合,交集和集合差異?我知道BitSet有它的方法,但這些在這裏不起作用。聯合,交集和設置差異的Java收集方法
public class Collections {
public static void main(String[] args) {
// 1. Collection
Set<Integer> grp1 = new HashSet<Integer>();
grp1.add(1);
grp1.add(2);
grp1.add(3);
grp1.add(4);
grp1.add(5);
// printing 1. collection
System.out.println("1. collection: ");
Iterator<Integer> i = grp1.iterator();
while(i.hasNext()) {
int numbers1 = i.next();
System.out.print(numbers1 + " ");
}
System.out.println();
// 2. collection
Set<Integer> grp2 = new HashSet<Integer>();
grp2.add(8);
grp2.add(7);
grp2.add(6);
grp2.add(5);
grp2.add(4);
// printing 2. collection
System.out.println("2. collection: ");
Iterator<Integer> y = grp2.iterator();
while(y.hasNext()) {
int numbers2 = y.next();
System.out.print(numbers2 + " ");
// Union
// Intersection
// Difference
}
}
}
我希望它的工作這種方式,但所有這些操作實際上是破壞性的,即它們就地工作,在現有的集合,它們都返回布爾值。你的代碼不幸的是不能編譯。我希望它。 –
我已經嘗試過那些,但沒有一個在Eclipse中工作:''Type mismatch:can not convert from boolean to Set''。編輯:像肖恩說,他們返回布爾值。 –
Daniel
啊真的!我忘了簽名!那些日子太多scala了:) –