HashSet类按照哈希算法来存取集合中的对象,具有良好的存取和查找性能。当向集合中加入一个对象时,HashSet会调用对象的hashCode()方法获得哈希码,然后根据这个哈希码进一步计算对象在集合中的存放位置。
import java.util.HashSet;
import java.util.Set;
class Person{
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public String toString() {
return "姓名:"+this.name+",年龄:"+this.age;
}
public boolean equals(Object o) {
if(this==o)return true;
if(!(o instanceof Person))return false;
final Person other=(Person)o;
if(this.name.equals(other.getName())&&this.age==other.getAge())
return true;
else
return false;
}
public int hashCode() {
int result;
result=(name==null?0:name.hashCode());
result=29*result+age;
return result;
}
}
public class Test {
public static void main(String[] args) {
Set<Person>set=new HashSet<Person>();
Person per1=new Person("Tom",15);
Person per2=new Person("Tom",15);
Person per3=per2;
set.add(per1);
set.add(per2);
set.add(per3);
System.out.println(set.size());
}
}