How HashMap works in Java
How HashMap works in Java?
HashMap in Java works on hashing principle, In hashing, hash functions are used to link key and value in HashMap Objects.
Internal DataStrature is hashTable , it woks key and value pair .
How HashMap Internally Works in Java ?
HashMap in Java works on hashing principle, In hashing, hash functions are used to link key and value in HashMap Objects.
What will happen if two different objects have the same hashcode?
two unequal objects in Java can have same hashcode , Since hashcode is same, bucket location would be same and collision will occur in HashMap Since HashMap uses LinkedList to store object, this entry (object of Map.Entry comprise key and value ) will be stored in LinkedList
it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals()
.
Equals and hashCode contract in Java
1) If two objects are equal by equals() method then there hashcode must be same.
2) If two objects are not equal by equals() method then there hashcode could be same or different.
How will you retrieve Value object if two Keys will have the same hashcode?
it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals()
.
Equals and hashCode contract in Java
1) If two objects are equal by equals() method then there hashcode must be same.
2) If two objects are not equal by equals() method then there hashcode could be same or different.
Why String, Integer and other wrapper classes are considered good keys?
String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final, and overrides equals and hashcode() method.
Can we use any custom object as a key in HashMap?
Of course you can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If the custom object is Immutable than this will be already taken care because you can not change it once created.
Can we use ConcurrentHashMap in place of Hashtable?
Hashtable is synchronized but ConcurrentHashMap provides better concurrency by only locking portion of map determined by concurrency level. ConcurrentHashMap is certainly introduced as Hashtable and can be used in place of it, but Hashtable provides stronger thread-safety than ConcurrentHashMap
How null key is handled in HashMap? Since equals() and hashCode() are used to store and retrieve values, how does it work in case of the null key?
In short, equals() and hashcode() method are not used in case of null keys in HashMap