import java.util.HashSet;
import java.util.Iterator;
/*
* 往hashSet集合中存入对象
* 姓名和年龄视为重复元素。
*
*
* */
public class hashSet {
public static void main(String[] args){
HashSet hs = new HashSet();
hs.add(new person("one",20));
hs.add(new person("two",20));
hs.add(new person("one",20));
hs.add(new person("san",22));
hs.add(new person("san",22));
hs.add(new person("san",23));
//迭代器,输出集合。
Iterator it = hs.iterator();
while(it.hasNext()){
person p = (person)it.next();
System.out.println(p.getName()+"___"+p.getAge());
}
}
}
class person{
private String name;
private int age;
person(String name , int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
//hashCode方法
public int hashCode(){
return name.hashCode()+age;
}
//自定义比较方法,比较名字和年龄。
public boolean equals(Object obj){
if(!(obj instanceof person))
return false;
person p = (person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
}
复写equals方法这样代码阅读性比较高吧
if(!(obj instanceof person))
return false;
person p = (person)obj;
return this.name.equals(p.name) && this.age == p.age;
判断的时候写错了,比较时出错 |