Java HashSet contains()
Java HashSet类的
contains()方法用于检查此HashSet是否包含指定的元素。
语法
以下是
contains()方法的声明:
public boolean contains(Object o)
参数
参数 |
说明 |
必需/可选 |
o |
这是要在此集合中进行测试的元素。 |
必需 |
返回
如果此集合包含指定的元素,则
contains()方法将返回true。
异常
不适用
兼容版本
Java 1.2及更高版本
示例1
import java.util.*;
public class HashSetContainsExample1 {
public static void main(String[] args) {
HashSet<Integer> hset = new HashSet<Integer>();
hset.add(11);
hset.add(21);
hset.add(15);
hset.add(110);
hset.add(151);
System.out.println("Hash set Elements: "+ hset);
System.out.println("Does the Set contains '110'? :- "+hset.contains(110));
System.out.println("Does the Set contains '555'? :- "+hset.contains(555));
}
}
输出:
Hash set Elements: [21, 151, 11, 110, 15]
Does the Set contains '110'? :- true
Does the Set contains '555'? :- false
示例2
import java.util.*;
public class HashSetContainsExample2 {
public static void main(String[] args) {
@SuppressWarnings("rawtypes")
HashSet studentSet = init();
System.out.print("Enter student name:");
Scanner s = new Scanner(System.in);
String name = s.nextLine();
s.close();
student database
if(studentSet.contains(name)){
System.out.println(name +" found on student list.");
}
else{
System.out.println(name +" name not on the student list.");
}
}
@SuppressWarnings("rawtypes")
private static HashSet init() {
HashSet<String> studentSet = new HashSet<>();
studentSet.add("Rishi");
studentSet.add("Sharon");
studentSet.add("Pawan");
return studentSet;
}
}
输出:
Enter student name: Rishi
Rishi found on student list.
示例3
import java.util.*;
public class HashSetContainsExample3 {
public static void main(String[] args) {
HashSet<> hashset = new HashSet<String>();
hashset.add("Facebook");
hashset.add("Twitter");
hashset.add("Instagram");
System.out.println("Elements of the HashSet:");
for(String val : hashset)
{
System.out.println(val);
}
System.out.println("Does the HashSet contains 'Whatsapp'? :- "+hashset.contains("Whatsapp"));
System.out.println("Does the HashSet contains 'Facebook'? :- "+hashset.contains("Facebook"));
}
}
输出:
Elements of the HashSet:
Twitter
Instagram
Facebook
Does the HashSet contains 'Whatsapp'? :- false
Does the HashSet contains 'Facebook'? :- true