1

Is there any way i can count number of elements landing in same Bucket in HashSet. I wish to write a program that can count no of elements landing in same bucket in HashSet

swati
  • 61
  • 4
  • 3
    @user1121883 That's not correct. `HashSet` is built on `HashMap`, which re-hashes the hashcodes provided by `hashCode()`. – user207421 Jan 12 '15 at 08:56

1 Answers1

2

HashSet is backed by a HashMap. The HashMap (source) contains an array (called table) of Entry objects, and each Entry has a next field, which can be used to form a linked list of entries for that bucket.

So you can count the number of elements by inspecting these data structures, following the chain of Entries and counting them.

table has default (package) access, i.e. it is non-public, so you will need to use reflection to 'break into' the class by setting the access to public. This process is described in this question, for example.

Alternatively, you could create your own version of HashSet, based on the JDK source code, but with public access to the fields that you need to inspect.

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146
  • 1
    That would require accessing non public members of HashMap, which can only be done with reflection. – Eran Jan 12 '15 at 08:55
  • 1
    You can also place your *inspection-code* in the same package as the `HashMap` (i.e. `java.util`). The you do not need reflection but can access the `table` property directly. Not pretty, I know but reflection is not pretty either ;) – wassgren Jan 12 '15 at 09:04
  • Yes, that's probably much easier. – DNA Jan 12 '15 at 09:07
  • @DNA Can you elaborate by taking some example – swati Jan 12 '15 at 09:31
  • Found [this SO](http://stackoverflow.com/questions/3804442/why-java-lang-securityexception-prohibited-package-name-java-is-required), it is **not** allowed to put classes in the *java*-package so unfortunately that will not work. – wassgren Jan 12 '15 at 09:34
  • @DNA So, I took the liberty to remove that part from the answer. – wassgren Jan 12 '15 at 09:43