I have this statement about java equals and hashcode.
if we were to use such an Integer object for a key in a HashMap, we would not be able to reliably retrieve the associated value
what it means ? why it says 'not reliably' ? I write a test program, it always works.
public class Test1 {
public static void main(String[] args){
Map<Integer, Student> map = new HashMap<Integer, Student>();
map.put(1, new Student("john"));
map.put(2, new Student("peter"));
Student s1 = map.get(1);
Student s2 = map.get(1);
Student s3 = map.get(2);
System.out.println("s1:"+s1+" s2:"+s2+" s3:"+s3);
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s2));
}
}
class Student{
private String name;
public Student(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}