public class Person {
public String firstName;
public String lastName;
public int age;
public Person(String f, String l, int a)
{
firstName = f;
lastName = l;
age = a>0?a:0;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
public int hashCode()
{
//System.out.println(firstName.hashCode() + lastName.hashCode() + age * 37);
return firstName.hashCode() + lastName.hashCode() + age * 37;
}
/**
* 当hash值相同时,会比较equals,默认比较内容是内存地址
* 这里必须被重写,否则HashTree 的equals方法只会比较地址值,因为两个实例的地址值
* 都不相同,所以内容相同的元素也会被判断为不相同而现实出来
*/
public boolean equals(Object obj)
{
if ( !(obj instanceof Person))
return false;
else
{
Person p = (Person) obj;
if (p.getAge() == age && p.getFirstName() == firstName &&
p.getLastName() == lastName)
return true;
else
return false;
}
}
}
import java.util.*;
public class HashTest {
HashSet<Person> hs = new HashSet<Person>();
public void add()
{
hs.add( new Person("Z1","S1",21) );
hs.add( new Person("Z2","S2",22) );
hs.add( new Person("Z3","S3",23) );
hs.add( new Person("Z","S",22) );
hs.add( new Person("Z1","S1",21) );
Iterator it = hs.iterator();
while (it.hasNext())
{
Person tempPerson = (Person)it.next();
System.out.printf("%-6s %-6s %d \n", tempPerson.getFirstName(),
tempPerson.getLastName(), tempPerson.getAge() );
}
}
public static void main(String[] argc)
{
HashTest ht =new HashTest();
ht.add();
}
}
output
Z S 22
Z3 S3 23
Z1 S1 21
Z2 S2 22