Java.util.Set.clear()方法用于从Set中删除所有元素。使用clear()方法仅清除集合中的所有元素,而不删除集合。换句话说,可以说clear()方法仅用于清空现有Set。
用法:
void clear()
参数:该方法不带任何参数
返回值:该方法不返回任何值。
以下示例程序旨在说明Java.util.method.clear()方法:
// Java code to illustrate clear()
import java.io.*;
import java.util.*;
public class SetDemo {
public static void main(String args[])
{
// Creating an empty Set
Set st = new HashSet();
// Use add() method to add elements into the Set
st.add("Welcome");
st.add("To");
st.add("Geeks");
st.add("4");
st.add("Geeks");
// Displaying the Set
System.out.println("Initial Set: " + st);
// Clearing the Set using clear() method
st.clear();
// Displaying the final Set after clearing;
System.out.println("The final set: " + st);
}
}
输出:
Initial Set: [4, Geeks, Welcome, To]
The final set: []