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

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

Java中的 AbstractCollection clear() 方法及示例

Java Javaclear()方法用于从 Collection 中删除所有元素。使用 clear() 方法只会清除集合中的所有元素,不会删除集合。换句话说,可以说 clear() 方法仅用于清空现有的 AbstractCollection。

句法:

AbstractCollection.clear()

返回值:该函数不返回任何值。

下面的程序说明了 AbstractCollection.clear() 方法:

方案一:

// Java code to illustrate clear(Object o)
// of AbstractCollelction
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String[] args)
    {
  
        // Create an empty Collection
        AbstractCollection
            abs = new ArrayList();
  
        // Use add() method to add
        // elements in the collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("4");
        abs.add("Geeks");
  
        // Displaying the Collection
        System.out.println("AbstractCollection: "
                           + abs);
  
        // Clearing the Collection
        abs.clear();
  
        // Displaying the Collection
        System.out.println("AbstractCollection "
                           + "after using clear: "
                           + abs);
    }
}
输出:
AbstractCollection: [Welcome, To, Geeks, 4, Geeks]
AbstractCollection after using clear: []

方案二:

// Java code to illustrate clear(Object o)
// of AbstractCollelction
  
import java.util.*;
import java.util.AbstractCollection;
  
public class AbstractCollectionDemo {
    public static void main(String[] args)
    {
  
        // Create an empty collection
        AbstractCollection
            abs = new LinkedList();
  
        // Use add() method to add
        // elements in the collection
        abs.add(15);
        abs.add(20);
        abs.add(25);
        abs.add(30);
        abs.add(35);
  
        // Displaying the Collection
        System.out.println("AbstractCollection: "
                           + abs);
  
        // Clearing the Collection
        abs.clear();
  
        // Displaying the Collection
        System.out.println("AbstractCollection "
                           + "after using clear: "
                           + abs);
    }
}
输出:
AbstractCollection: [15, 20, 25, 30, 35]
AbstractCollection after using clear: []