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


Java AbstractSet clear()用法及代碼示例


Java中的AbstractSet的clear()方法用於從集中刪除所有元素。該調用返回後,該集合將為空。

用法:

public void clear()

參數:此函數沒有參數。


返回值:該方法不返回任何值。它刪除集合中的所有元素並使其為空。

以下示例說明了AbstractSet.clear()方法:

示例1:

// Java code to demonstrate the working of 
// clear() method in AbstractSet 
  
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // creating an AbstractSet 
        AbstractSet<Integer> arr 
            = new TreeSet<Integer>(); 
  
        // using add() to initialize values 
        // [1, 2, 3, 4] 
        arr.add(1); 
        arr.add(2); 
        arr.add(3); 
        arr.add(4); 
  
        // set initially 
        System.out.println("The set initially: "
                           + arr); 
  
        // clear function used 
        arr.clear(); 
  
        // set after clearing all elements 
        System.out.println("The set after "
                           + "using clear() method: "
                           + arr); 
    } 
}
輸出:
The set initially: [1, 2, 3, 4]
The set after using clear() method: []

示例2:

// Java code to demonstrate the working of 
// clear() method in AbstractSet 
  
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // creating an AbstractSet 
        AbstractSet<String> arr 
            = new TreeSet<String>(); 
  
        // using add() to initialize values 
        // [Geeks, For, ForGeeks, GeeksForGeeks] 
        arr.add("Geeks"); 
        arr.add("For"); 
        arr.add("ForGeeks"); 
        arr.add("GeeksForGeeks"); 
  
        // set initially 
        System.out.println("The set initially: "
                           + arr); 
  
        // clear function used 
        arr.clear(); 
  
        // set after clearing all elements 
        System.out.println("The set after "
                           + "using clear() method: "
                           + arr); 
    } 
}
輸出:
The set initially: [For, ForGeeks, Geeks, GeeksForGeeks]
The set after using clear() method: []


相關用法


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