user3619843
user3619843

Reputation: 51

How to get all element of a bucket in HashMap

As we know HashMap keep all data in buckets(calculate bucket location on basis of hashCode()).

is there any way to get all element of bucket (without iterating whole bucket)

like

my hashCode()  method generates hashcode like (**bkt1,bkt2,bkt3 and bkt4**)
in **bkt1** we have values like (**val1,val2,val3 and val4**)
in **bkt2** we have values like ( **val5,val6 and val7**)
and so on ....

can i get all values of bucket bkt1 without iterating whole map

Upvotes: 4

Views: 2999

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 62179

You cannot get all elements of a bucket of a java HashMap. You cannot even get any elements of a bucket of a java HashMap. That's because the concept of a bucket is internal to the implementation of a HashMap, so it is not exposed by HashMap. There are no public methods of HashMap that deal with buckets in any way.

(And thank goodness for that! I don't want to even think how unnecessarily complicated the interface of HashMap would be if the concept of buckets was exposed.)

Since buckets are not exposed, you do not have any means of observing them other than with a debugger.

In order to have control over the buckets you would need to implement the hash map yourself. It is not terribly difficult, but it is not a walk in the park either. However, the chances of you coming up with a HashMap implementation that performs anywhere near as well as the built-in java HashMap are astronomically slim.

The only control you have over the buckets in a hash-map is indirect: it depends on how good your hash-function is. So, just make sure that your objects implement a good hash function.

A good hash function is a hash function which yields a wide distribution of hash values.

This will give you as many different buckets as possible, with as few elements in each bucket as possible, which is what you want for optimal performance.

In the general case, if you just build your hash function using Objects.hash( ... ) like everyone else, your hash function will be just fine. You can check how wide the distribution is by examining how often it yields the same hash-code for two different keys. In the general case, you will find that very seldom, if ever, does it yield the same hash-code for two different keys, so everything is good.

No need to be worrying about things that are quite good as they are.

Upvotes: 7

Tarik
Tarik

Reputation: 5031

In addition to Mike Nakis's answer, if your intention is just to get an object from a Map via an index, use the interface methode Object get(key).

Upvotes: 0

Related Questions