本帖最后由 黑马任雪刚 于 2012-6-6 17:54 编辑
//为什么程序中的hashCode()和equals()没有调用就自动运行了,这两个方法在java底层是怎样的一个运行过程??????
import java.util.*;
class Students
{
private int age;
private String name;
Students(String name,int age)
{
this.age = age;
this.name = name;
}
public int hashCode()
{
//System.out.println(this.getName()+"hashCode");
return name.hashCode()+age*37;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Students))
return false;
Students s = (Students)obj;
return this.name.equals(s.name)&&this.age==s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
public class lizi
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
HashSet hs = new HashSet();
hs.add(new Students("a1",21));
hs.add(new Students("a2",24));
hs.add(new Students("a3",33));
hs.add(new Students("a2",78));
hs.add(new Students("a3",33));
Iterator it = hs.iterator();
while(it.hasNext())
{
Students s = (Students)it.next();
sop(s.getName()+"..."+s.getAge());
}
}
}
|