📌  相关文章
📜  Java中的 AbstractList clear() 方法及示例

📅  最后修改于: 2022-05-13 01:54:18.632000             🧑  作者: Mango

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
            AbstractList
                arrlist1 = new ArrayList();
  
            // 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
            AbstractList
                arrlist1 = new ArrayList();
  
            // 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 : []