Java 資料結構 - 集合的差集
假設我們透過新增兩個(或多個)集合的內容來建立了一個集合物件,當您需要完全從該集合中刪除特定集合的內容時,可以使用 removeAll() 方法來實現。
此方法屬於 Set 介面,並且繼承自 Collection 介面。它接受一個集合物件,並立即從當前 Set(物件)中完全刪除其內容。
示例
import java.util.HashSet;
import java.util.Set;
public class SubtractingTwoSets {
public static void main(String args[]) {
Set set1 = new HashSet();
set1.add(100);
set1.add(501);
set1.add(302);
set1.add(420);
System.out.println("Contents of set1 are: ");
System.out.println(set1);
Set set2 = new HashSet();
set2.add(200);
set2.add(630);
set2.add(987);
set2.add(665);
System.out.println("Contents of set2 are: ");
System.out.println(set2);
set1.addAll(set2);
System.out.println("Contents of set1 after addition: ");
System.out.println(set1);
set1.removeAll(set2);
System.out.println("Contents of set1 after removal");
System.out.println(set1);
}
}
輸出
Contents of set1 are: [100, 420, 501, 302] Contents of set2 are: [630, 200, 665, 987] Contents of set1 after addition: [100, 420, 501, 630, 200, 665, 987, 302] Contents of set1 after removal [100, 420, 501, 302]
廣告