一个关于hashCode 与equals的问题
import java.util.HashSet;
import java.util.Iterator;
class HashSetTest
{
HashSet<Student> hs =new HashSet<Student>();
public void put(Student o)
{
hs.add(o);
}
public void print()
{
Iterator<Student> it=hs.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
public static void main(String[] args)
{
HashSetTest hs1=new HashSetTest();
hs1.put(new Student(1,"fenhua1"));
hs1.put(new Student(4,"fenhua4"));
hs1.put(new Student(3,"wufeng"));
hs1.put(new Student(3,"wufeng"));
hs1.print(); /*我在Student类中虽然重写了hashCode(),equals(),但我在main()中并没有调用他们,为什么我输入两个new Student(3,"wufeng")对象到 hs1中,最终结果输出的只有一个3 :wufeng 补充:我已经明白有hashCode()和equals()方法能得到同一个内存地址,我想问的是,我没调用他们,怎么就实现了new Student(3,"wufeng"在内存中就得到了同一内存地址?
}
}
class Student
{
Integer num;
String name;
Student(Integer num, String name)
{
this.num=num;
this.name=name;
}
public String toString()
{
return num+":"+name;
}
public int hashCode()
{
return num*name.hashCode();
}
/* public boolean equals(Object obj)
{
if(obj instanceof Student){
Student s = (Student)obj;
return num == s.num && name.equals(s.name);
}*/
public boolean equals(Object obj)
{
Student s = (Student)obj;
return num == s.num && name.equals(s.name);
}
}