"What will happen if two different objects have same hashcode?”
Now from here onwards real confusion starts, Some time candidate will say that since hashcode is equal, both objects are equal and HashMap will throw exception or not store them again etc, Then you might want to remind them about equals() and hashCode() contract that two unequal object in Java can have same hashcode. Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would be same and collision will occur in HashMap, Since HashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value ) will be stored in LinkedList. Great this answer make sense though there are many collision resolution methods available this is simplest and HashMap in Java does follow this. But story does not end here and interviewer asks
No. It is one per K‑V pair.Harshana Dias wrote: . . . This Entry class creates per hash bucket right?
Campbell Ritchie wrote:
No. It is one per K‑V pair.Harshana Dias wrote: . . . This Entry class creates per hash bucket right?
Campbell Ritchie wrote:What is not concrete about that? That is the usual way a linked list is implemented: a self‑referential class which has an instance of itself as the next field.
Not quite.Harshana Dias wrote: . . . ok multiple Entry objects in same buckets for duplicate hashcode key objects right
Campbell Ritchie wrote:
The map implementations usually use abs(h % c) where h is the hashcode and c the capacity of the backing array.
No.Harshana Dias wrote: . . . In here you mean by backing array is the linked list type of implementation of the Entry class right?
I am going to test your electrical conductivity with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|