📌  相关文章
📜  Java中的 CopyOnWriteArraySet clear() 方法

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

Java中的 CopyOnWriteArraySet clear() 方法

CopyOnWriteArraySetclear()方法会擦除 Set 中的所有元素。调用函数后,Set 的大小变为零。

句法:

public void clear()

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

下面的程序说明了上述函数:

方案一:

// Java Program to illustrate the CopyOnWriteArraySet
// clear() method in Java
  
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArraySet
        CopyOnWriteArraySet ArrSet
            = new CopyOnWriteArraySet();
  
        // Add elements
        ArrSet.add(32);
        ArrSet.add(67);
        ArrSet.add(98);
        ArrSet.add(98);
  
        // print CopyOnWriteArraySet
        System.out.println("CopyOnWriteArraySet: "
                           + ArrSet);
  
        // Clear the CopyOnWriteArraySet
        // Using clear() method
        ArrSet.clear();
  
        System.out.println("\nCopyOnWriteArraySet cleared\n");
  
        // Print the updated CopyOnWriteArraySet
        System.out.println("Updated CopyOnWriteArraySet: "
                           + ArrSet);
    }
}
输出:
CopyOnWriteArraySet: [32, 67, 98]

CopyOnWriteArraySet cleared

Updated CopyOnWriteArraySet: []

方案二:

// Java Program to illustrate the CopyOnWriteArraySet
// clear() method in Java
  
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArraySet
        CopyOnWriteArraySet ArrSet
            = new CopyOnWriteArraySet();
  
        // Add elements
        ArrSet.add("gopal");
        ArrSet.add("gfg");
        ArrSet.add("jgec");
        ArrSet.add("jgec");
  
        // print CopyOnWriteArraySet
        System.out.println("CopyOnWriteArraySet: "
                           + ArrSet);
  
        // Clear the CopyOnWriteArraySet
        // Using clear() method
        ArrSet.clear();
  
        System.out.println("\nCopyOnWriteArraySet cleared\n");
  
        // Print the updated CopyOnWriteArraySet
        System.out.println("Updated CopyOnWriteArraySet: "
                           + ArrSet);
    }
}
输出:
CopyOnWriteArraySet: [gopal, gfg, jgec]

CopyOnWriteArraySet cleared

Updated CopyOnWriteArraySet: []

参考: https: Java/util/concurrent/CopyOnWriteArraySet.html#clear–