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


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


java.util.Collection接口的clear()用於清除調用它的Collection。此方法不帶任何參數,也不返回任何值。

用法:

Collection.clear()

參數:此方法不接受任何參數


返回值:此方法不返回任何值。

異常:此方法引發以下異常:

  • UnsupportedOperationException:如果此集合不支持添加操作

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

示例1:使用LinkedList類

// Java code to illustrate boolean clear() method 
  
import java.io.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String args[]) 
    { 
  
        // creating an empty LinkedList 
        Collection<String> list = new LinkedList<String>(); 
  
        // use add() method to add elements in the list 
        list.add("Geeks"); 
        list.add("for"); 
        list.add("Geeks"); 
  
        // Output the present list 
        System.out.println("The list is: " + list); 
  
        // Clearing the LinkedList 
        list.clear(); 
  
        // printing the new list 
        System.out.println("The new List is: " + list); 
    } 
}
輸出:
The list is: [Geeks, for, Geeks]
The new List is: []

示例2:使用ArrayDeque類

// Java code to illustrate clear() method 
  
import java.util.*; 
  
public class ArrayDequeDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty ArrayDeque 
        Collection<String> de_que = new ArrayDeque<String>(); 
  
        // Use add() method to add elements into the Deque 
        de_que.add("Welcome"); 
        de_que.add("To"); 
        de_que.add("Geeks"); 
        de_que.add("4"); 
        de_que.add("Geeks"); 
  
        // Displaying the ArrayDeque 
        System.out.println("ArrayDeque: " + de_que); 
  
        // Clearing the ArrayDeque 
        de_que.clear(); 
  
        // printing the new ArrayDeque 
        System.out.println("The new ArrayDeque is: "
                           + de_que); 
    } 
}
輸出:
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The new ArrayDeque is: []

示例3:使用ArrayList類

// Java code to illustrate clear() method 
  
import java.io.*; 
import java.util.*; 
  
public class ArrayListDemo { 
    public static void main(String[] args) 
    { 
  
        // create an empty array list with an initial capacity 
        Collection<Integer> arrlist = new ArrayList<Integer>(5); 
  
        // use add() method to add elements in the list 
        arrlist.add(15); 
        arrlist.add(20); 
        arrlist.add(25); 
  
        // prints all the elements available in list 
        System.out.println("ArrayList: " + arrlist); 
  
        // Clearing the ArrayList 
        arrlist.clear(); 
  
        // printing the new ArrayList 
        System.out.println("The new ArrayList is: "
                           + arrlist); 
    } 
}
輸出:
ArrayList: [15, 20, 25]
The new ArrayList is: []

參考: https://docs.oracle.com/javase/9/docs/api/java/util/Collection.html#clear–



相關用法


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