📜  Java中的 LinkedHashSet clear() 方法及示例

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

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

Java.util.LinkedHashSet类的clear()方法用于从该集合中删除所有元素。此调用返回后,该集合将为空。

句法:

public void clear()

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

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

示例 1:

// Java program to demonstrate
// clear() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // Create the object of LinkedHashSet
            LinkedHashSet
                linkset = new LinkedHashSet();
  
            // populate hash set
            linkset.add(10);
            linkset.add(20);
            linkset.add(30);
  
            // print the LinkedHashSet
            System.out.println("LinkedHashSet: "
                               + linkset);
  
            // clear set values
            // using clear() method
            linkset.clear();
  
            // print the LinkedHashSet
            System.out.println("LinkedHashSet after "
                               + "use of clear() method: "
                               + linkset);
        }
  
        catch (NullPointerException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
LinkedHashSet: [10, 20, 30]
LinkedHashSet after use of clear() method: []

示例 2:

// Java program to demonstrate
// clear() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // Create the object of LinkedHashSet
            LinkedHashSet
                linkset = new LinkedHashSet();
  
            // populate hash set
            linkset.add("A");
            linkset.add("B");
            linkset.add("C");
  
            // print the LinkedHashSet
            System.out.println("LinkedHashSet: "
                               + linkset);
  
            // clear set values
            // using clear() method
            linkset.clear();
  
            // print the LinkedHashSet
            System.out.println("LinkedHashSet after "
                               + "use of clear() method: "
                               + linkset);
        }
  
        catch (NullPointerException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
LinkedHashSet: [A, B, C]
LinkedHashSet after use of clear() method: []