Hash Collision or Hashing Collision in HashMap is not a new topic and I've come across several blogs and discussion boards explaining how to produce Hash Collision or how to avoid it in an ambiguous and detailed way. I recently came across this question in an interview. I had lot of things to explain but I think it was really hard to precisely give the right explanation. Sorry if my questions are repeated here, please route me to the precise answer:
- What exactly is Hash Collision - is it a feature, or common phenomenon which is mistakenly done but good to avoid?
- What exactly causes Hash Collision - the bad definition of custom class'
hashCode()
method, OR to leave theequals()
method un-overridden while imperfectly overriding thehashCode()
method alone, OR is it not up to the developers and many popular java libraries also has classes which can cause Hash Collision? - Does anything go wrong or unexpected when Hash Collision happens? I mean is there any reason why we should avoid Hash Collision?
- Does Java generate or at least try to generate unique hashCode per class during object initiation? If no, is it right to rely on Java alone to ensure that my program would not run into Hash Collision for JRE classes? If not right, then how to avoid hash collision for hashmaps with final classes like String as key?
I'll be greateful if you could please share you answers for one or all of these questions.
HashMap
uses is to maintain a tree of colliding values (used to be a list of values). If you find yourself having too many collisions, you might want to consider resizing the number of buckets in your hashmap. And your question is too broad, I agree with the other comments, you should narrow down what you want to ask here. – Jennee