Java Set clear()方法及实例
Java.util.Set.clear()方法用于从一个集合中删除所有的元素。使用clear()方法只是清除集合中的所有元素,而不是删除该集合。换句话说,我们可以说clear()方法只是用来清空一个现有的集合。
语法
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<String> st = new HashSet<String>();
// 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: []
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#clear()