使用contains()
方法检查特定元素是否存在-
Set<Integer> hs = new HashSet<Integer>(); hs.add(30); hs.add(67); hs.add(88); hs.add(33); hs.add(54); hs.add(90); hs.add(66); hs.add(79);
要检查元素89,使用contains()
方法-
hs.contains(89));
以下是检查HashSet中是否存在特定元素的示例-
import java.util.*; public class Demo { public static void main(String args[]) { //创建哈希集 Set<Integer> hs = new HashSet<Integer>(); hs.add(30); hs.add(67); hs.add(88); hs.add(33); hs.add(54); hs.add(90); hs.add(66); hs.add(79); System.out.println("Elements in set = "+hs); System.out.println("Does 89 in the set? "+hs.contains(89)); System.out.println("Does 67 in the set? "+hs.contains(67)); } }
输出结果
Elements in set = [33, 66, 67, 54, 88, 90, 30, 79] Does 89 in the set? false Does 67 in the set? True