Is there a way to determine what buckets do we have in HashMap
, and how many entries do they contain?
Asked
Active
Viewed 1,319 times
1

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523

asdfzcx
- 25
- 1
- 8
-
hashmap -> keyset -> lenght? – Fran Montero Nov 05 '15 at 11:19
-
3@FranMontero this would get you all they keys, the OP is asking for the buckets – Sleiman Jneidi Nov 05 '15 at 11:23
-
@asdfzcx this link can help you http://stackoverflow.com/questions/18636576/what-is-meant-by-number-of-buckets-in-the-hashmap – Dev Nov 05 '15 at 11:35
2 Answers
2
Not directly: this is an implementation detail hidden through use of private fields.
If you have access to source code of your JDK, you could use reflection API to access private variables of your HashMap<K,V>
, which would let you get bucket count and the content of individual buckets. Your code would be non-portable, though, because it would break encapsulation of a library class.

Community
- 1
- 1

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
2
You can do it by reflection but it is very jdk specific. This one works with small maps Java 8 but will probably break when the map gets bigger because I believe Java 8 uses a hybrid mechanism when the buckets get full.
private void buckets(HashMap<String, String> m) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
// Pull out the table.
Field f = m.getClass().getDeclaredField("table");
f.setAccessible(true);
Object[] table = (Object[]) f.get(m);
int bucket = 0;
// Walk it.
for (Object o : table) {
if (o != null) {
// At least one in this bucket.
int count = 1;
// What's in the `next` field?
Field nf = o.getClass().getDeclaredField("next");
nf.setAccessible(true);
Object n = nf.get(o);
if (n != null) {
do {
// Count them.
count += 1;
} while ((n = nf.get(n)) != null);
}
System.out.println("Bucket " + bucket + " contains " + count + " entries");
}
bucket += 1;
}
}
public void test() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
HashMap<String, String> m = new HashMap<>();
String[] data = {"One", "Two", "Three", "Four", "five"};
for (String s : data) {
m.put(s, s);
}
buckets(m);
}
Prints:
Bucket 7 contains 2 entries
Bucket 13 contains 2 entries
Bucket 14 contains 1 entries

OldCurmudgeon
- 64,482
- 16
- 119
- 213