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


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


java.util.AbstractList 類的 clear() 方法用於從該列表中刪除所有元素。此調用返回後,列表將為空。

用法:

public void clear()

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

以下是說明 clear() 方法的示例。

範例1:




// Java program to demonstrate
// clear() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of AbstractList<String>
            AbstractList<String>
                arrlist1 = new ArrayList<String>();
  
            // Populating arrlist1
            arrlist1.add("A");
            arrlist1.add("B");
            arrlist1.add("C");
            arrlist1.add("D");
            arrlist1.add("E");
  
            // print the ArrayList
            System.out.println("Original ArrayListlist:"
                               + arrlist1);
  
            // Removing all the elements
            // using clear() method
            arrlist1.clear();
  
            // print the new ArrayList
            System.out.println("New ArrayList:"
                               + arrlist1);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown:"
                               + e);
        }
    }
}
輸出:
Original ArrayListlist:[A, B, C, D, E]
New ArrayList:[]

範例2:


// Java program to demonstrate
// clear() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of AbstractList<Integer>
            AbstractList<Integer>
                arrlist1 = new ArrayList<Integer>();
  
            // Populating arrlist1
            arrlist1.add(10);
            arrlist1.add(20);
            arrlist1.add(30);
            arrlist1.add(40);
            arrlist1.add(50);
  
            // print the ArrayList
            System.out.println("Original ArrayListlist:"
                               + arrlist1);
  
            // Removing all the elements
            // using clear() method
            arrlist1.clear();
  
            // print the new ArrayList
            System.out.println("New ArrayList:"
                               + arrlist1);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown:" + e);
        }
    }
}
輸出:
Original ArrayListlist:[10, 20, 30, 40, 50]
New ArrayList:[]




相關用法


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