问题
Ok just for knowledge , what significance it would made on Collection implementation classes like hashmap,hashset etc if the object's hashcode method always returns 0 in a demoClass. I know it has something to do with putForNullKey of hashmap or other classes of Collection implementation, but dont know much in details. I know for null objects the hascode is 0 so it has specfic method for 0 hashcode.
@Override
public int hashCode() {
return 0;
}
回答1:
It will make HashMap, HashSet and other collections that rely on hashCode very inefficient, since all elements/entries would be added to the same bin.
Methods such as get(), containsKey() and contains() would take O(n) instead of O(1).
BTW, the answer is not specific to a 0 hashCode. Any constant hashCode would behave exactly the same.
来源:https://stackoverflow.com/questions/29362401/what-is-the-impact-over-collection-implementations-when-hashcode-returns-zero