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
Asked
Active
Viewed 375 times
1 Answers
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.
-
1That would require accessing non public members of HashMap, which can only be done with reflection. – Eran Jan 12 '15 at 08:55
-
1You 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
-
-
-
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
-