what is the impact over Collection implementations

2019-07-23 19:49发布

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条回答
Explosion°爆炸
2楼-- · 2019-07-23 20:29

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.

查看更多
登录 后发表回答