要从HashSet中删除所有元素,请使用clear()
方法。
创建一个HashSet并初始化元素-
String strArr[] = { "P", "Q", "R", "S" }; Set s = new HashSet(Arrays.asList(strArr));
现在,删除所有上述元素-
s.clear()
以下是从HashSet中删除所有元素的示例-
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String[] a) { String strArr[] = { "P", "Q", "R", "S" }; Set s = new HashSet(Arrays.asList(strArr)); strArr = new String[] { "R", "S", "T", "U" }; s.addAll(Arrays.asList(strArr)); System.out.println("Elements = " +s); //删除所有元素 s.clear(); System.out.println("Set after removing all the elements = " +s); } }
输出结果
Elements = [P, Q, R, S, T, U] Set after removing all the elements = []