What Exactly is Hash Collision

前端 未结 4 2112
轻奢々
轻奢々 2020-12-13 20:55

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 t

4条回答
  •  天命终不由人
    2020-12-13 21:41

    What exactly is Hash Collision - is it a feature, or common phenomenon which is mistakenly done but good to avoid?

    Neither... both... it is a common phenomenon, but not mistakenly done, that is good to avoid.

    What exactly causes Hash Collision - the bad definition of custom class' hashCode() method, OR to leave the equals() method un-overridden while imperfectly overriding the hashCode() method alone, OR is it not up to the developers and many popular java libraries also has classes which can cause Hash Collision?

    by poorly designing your hashCode() method, you can produce too many collisions, leaving you equals method un-overridden should not directly affect the number of collisions, many popular java libraries have classes that can cause collisions (nearly all classes actually).

    Does anything go wrong or unexpected when Hash Collision happens? I mean is there any reason why we should avoid Hash Collision?

    There is degradation in performance, that is a reason to avoid them, but the program should continue to work.

    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?

    Java doesn't try to generate a unique hash code during object initialization, but it has a default implementation of hashCode() and equals(). The default implementation works to know whether two object references point to the same instance or not, and doesn't rely on the content (field values) of the objects. Therefore, the String class has its own implementation.

提交回复
热议问题