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;
}
}
You have misunderstood! Read the whole paragraph:
http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html
This is saying that the
Integerclass must have ahashCode()method andequals()in order to work. It does have those methods, so it’s fine. It will work.The example was saying that references to objects that store values should not be compared because two
Integerswith the same integer value may actually be different objects.x.equals(y)is always true.x == yis not always true (but can be sometimes). The rules change for different ranges of value. Never rely on==for any object references unless you are completely sure you know what you are doing.Also note that you are passing
intarguments (primitive types) notIntegers(references to objects) but your collection’s generic type isInteger. This means there is also boxing to throw into the equation!