Interview Question on java hashcode()
I recently attended an interview and was asked the following question.
There are two objects with same hashcode. I am inserting these two objects inside a hashmap.
hMap.put(a,a);
hMap.put(b,b);
where a.hashCode()==b.hashCode()
Now tell me how many objects will be there inside the hashmap?
I answered there will be only one object,since the hashcode开发者_开发问答s are equal the two objects will be equal and hashmap will not allow duplicate keys. Please tell me whether my understanding is correct or not?
There can be two different elements with the same hashcode. So your answer is incorrect. The only thing guaranteed is that if two elements have different hashcodes then they are different. When two elements have the same hashcode then Java uses the equals to further differentation.
So the answer is one or two objects.
There will either be one or two objects in the hashmap.
If the two objects are not equal, ie !a.equals(b)
, both will be stored.
No, the hashCode is an initial lookup for efficiency, but unless a.equals(b)==true
there will be two entries
There will be two objects in the hashmap, because they are not equals()
.
Here's the proof:
public static void main(String[] args) {
Object a = new Object() {
public int hashCode() {
return 1;
}
};
Object b = new Object() {
public int hashCode() {
return 1;
}
};
Map<Object, Object> map = new HashMap<Object, Object>();
map.put(a, a);
map.put(b, b);
System.out.println(map.size());
}
Output:
2
If I add an equals() method like this:
public boolean equals(Object obj) {
return obj.hashCode() == hashCode();
}
Output:
1
According to the javadoc for Object.equals():
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
This does not however mean that two objects that aren't equals()
can't share the same hashcode.
There are either one or two key objects depending on a.equals(b), and either one or two value objects depending on a==b.
精彩评论