當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java ConcurrentSkipListSet removeAll()用法及代碼示例


java.util.concurrent.ConcurrentSkipListSet的removeAll()方法是Java中的一個內置函數,該函數從該集合中移除指定集合中包含的所有元素。如果指定的集合也是一個集合,則此操作會有效地修改此集合,以使其值為兩個集合的非對稱集合差異。

用法:

public boolean removeAll(Collection> c)

參數:該函數接受單個參數c


返回值:如果此設置由於調用而改變,則函數返回true。

異常:該函數引發以下異常:

  • ClassCastException–如果該集合中一個或多個元素的類型與指定的集合不兼容
  • NullPointerException –如果指定的集合或其任何元素為空

以下示例程序旨在說明ConcurrentSkipListSet.removeAll()方法:

示例1:

// Java program to demonstrate removeAll() 
// method of ConcurrentSkipListSet 
  
import java.util.concurrent.*; 
import java.util.ArrayList; 
import java.util.List; 
  
class ConcurrentSkipListSetremoveAllExample1 { 
    public static void main(String[] args) 
    { 
  
        // Initializing the List 
        List<Integer> list = new ArrayList<Integer>(); 
  
        // Adding elements in the list 
        for (int i = 1; i <= 10; i += 2) 
            list.add(i); 
  
        // Contents of the list 
        System.out.println("Contents of the list: " + list); 
  
        // Initializing the set 
        ConcurrentSkipListSet<Integer> 
            set = new ConcurrentSkipListSet<Integer>(); 
  
        // Adding elements in the set 
        for (int i = 1; i <= 10; i++) 
            set.add(i); 
  
        // Contents of the set 
        System.out.println("Contents of the set: " + set); 
  
        // Remove all elements from the set which are in the list 
        set.removeAll(list); 
  
        // Contents of the set after removal 
        System.out.println("Contents of the set after removal: "
                           + set); 
    } 
}
輸出:
Contents of the list: [1, 3, 5, 7, 9]
Contents of the set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Contents of the set after removal: [2, 4, 6, 8, 10]

示例2:在removeAll()中顯示NullPOinterException的程序。

// Java program to demonstrate removeAll() 
// method of ConcurrentSkipListSet 
  
import java.util.concurrent.*; 
import java.util.ArrayList; 
import java.util.List; 
  
class ConcurrentSkipListSetremoveAllExample1 { 
    public static void main(String[] args) 
    { 
  
        // Initializing the set 
        ConcurrentSkipListSet<Integer> 
            set = new ConcurrentSkipListSet<Integer>(); 
  
        // Adding elements in the set 
        for (int i = 1; i <= 10; i++) 
            set.add(i); 
  
        // Contents of the set 
        System.out.println("Contents of the set: " + set); 
  
        try { 
            // Remove all elements from the set which are null 
            set.removeAll(null); 
        } 
        catch (Exception e) { 
            System.out.println("Exception: " + e); 
        } 
    } 
}
輸出:
Contents of the set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Exception: java.lang.NullPointerException

參考:



相關用法


注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 ConcurrentSkipListSet removeAll() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。