实例代码如下:
package 集合;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetTest01 {
public static void main(String[] args) {
HashSet hs = new HashSet();//hashSet底层自动调用hashCode()方法和equals()方法
hs.add(new Person1("lisi1",34));
hs.add(new Person1("lisi2",32));
hs.add(new Person1("lisi3",33));
hs.add(new Person1("lisi1",34));
Iterator it = hs.iterator();
while(it.hasNext()){
Person1 person = (Person1)it.next();
System.out.println(person.getName()+"::"+person.getAge());
}
}
}
class Person1{
private String name;
private int age;
Person1(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int hashCode() {
return name.hashCode()+age*39;//最好要乘以39,增加值的范围
}
public boolean equals(Object obj) {
if(!(obj instanceof Person1))
return false;
Person1 person = (Person1)obj;
return this.name.equals(person.name) && this.age == person.age;
}
}