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
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
.