import java.util.*;
class HashCodeDemo
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add(new Person("a1",11));
hs.add(new Person("a2",12));
hs.add(new Person("a3",13));
hs.add(new Person("a4",14));
Iterator it=hs.iterator();
while (it.hasNext())
{
Person p =(Person)it.next();
sop(p.getName()+"+++"+p.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Person
{
private String name;
private int age;
Person (String name,int age)
{
this.name=name;
this.age=age;
}
public int hashCode()//根据对象条件建立哈希值。描述事物需要往集合里存事物都要复写
{
System.out.println(this.name+"....hashCode");
return name.hashCode()+age*39;//乘以一个数值返回来一个值随意
}
public boolean equals(Object obj)//覆盖这个方法
{
if (!(obj instanceof Person))
//return false;//错误返回false这个没有意义,就直接抛异常
throw return new ClassCastException("类型不匹配")
Person p=(Person)obj;
System.out.println(this.name+".equals..."+p.name);
return this.name.equals(p.name)&&this.age==p.age;//这里能不能换成this.age.equals(p.age)啊?为什么要用==啊
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
} |