Hashcode bucket distribution in java

前端 未结 3 1002
终归单人心
终归单人心 2021-01-05 15:37

Suppose I need to store 1000 objects in Hashset, is it better that I have 1000 buckets containing each object( by generating unique value for hashcode for each object) or ha

3条回答
  •  隐瞒了意图╮
    2021-01-05 16:02

    Object.hashCode()are of type int, you can only have 2^32 different values that's why you create buckets and distribute objects among them.

    Edit: If you are using 2^32 buckets to store 2^32 object then defiantly get operations will give you constant complexity but when you are inserting one by one element to store 2^32 objects then rehashing will perform than means if we are using Object[] as buckets then each time it exceeds the length of array it will create new array with greater size and copy elements into this. this process will increase complexity. That's why we make use of equals and hashcode in ratio and that is done by Hashsets itself by providing better hashing algorithm.

提交回复
热议问题