public class Test {
public static void main(String[] args) {
HashSet l=new HashSet();
Students s1=new Students("zhang1",12);
Students s2=new Students("zhang1",11);
System.out.println(s1==s2);
l.add(s1);
l.add(s2);
Iterator it=l.iterator();
System.out.println();
while(it.hasNext()){
Students p=(Students)it.next();
System.out.println(p.getName()+"..."+p.getAge());
}
System.out.println(s1);
System.out.println(s2);
}
}
public class Students {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Students(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int hashCode() {
System.out.println("hashcode running...");
return name.hashCode();
}
public boolean equals(Object obj) {
Students s=(Students)obj;
System.out.println(this);
return this.name==s.name && this.age==s.age;
}
}
输出结果:
false
hashcode running...
hashcode running...
hashcode running...
Test.Students@d61689c5
zhang1...11
zhang1...12
hashcode running...
Test.Students@d61689c5
hashcode running...
Test.Students@d61689c5
问题1:Test类中最后两句话打印s1和s2的地址,结果都是
Test.Students@d61689c5,为什么地址会一样?可是通过s1==s2发现地址是不一样的。
问题2:输出对象的时候,为什么会调用hashcode方法?