what is the impact over Collection implementations when hashcode() returns zero

久未见 提交于 2020-01-15 05:08:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!