java集合中的contain方法用来判断是否存在某个元素,编写的代码如下:
import java.util.HashSet;
class Dog{
String color;
public Dog(String s){
color = s;
}
}
public class SetAndHashCode {
public static void main(String[] args) {
HashSet<Dog> dogSet = new HashSet<Dog>();//新建一个set集合
dogSet.add(new Dog("white"));//添加元素
dogSet.add(new Dog("white"));
System.out.println("We have " + dogSet.size() + " white dogs!");
if(dogSet.contains(new Dog("white"))){//contain判断是否存在某个元素
System.out.println("We have a white dog!");
}else{
System.out.println("No white dog!");
}
}
}