【问题标题】:Number of entries in HashMap bucketHashMap 桶中的条目数
【发布时间】:2016-02-06 04:55:24
【问题描述】:

有没有办法确定我们在HashMap 中有哪些桶,它们包含多少条目?

【问题讨论】:

标签: java hashmap bucket


【解决方案1】:

你可以通过反射来做到这一点,但它是非常特定于 jdk 的。这适用于 Java 8 的小型地图,但当地图变大时可能会中断,因为我相信 Java 8 在桶装满时使用混合机制。

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);
}

打印:

Bucket 7 contains 2 entries
Bucket 13 contains 2 entries
Bucket 14 contains 1 entries

【讨论】:

    【解决方案2】:

    不直接:这是通过使用私有字段隐藏的实现细节。

    如果您可以访问 JDK 的源代码,则可以使用 reflection API 访问 private variablesHashMap&lt;K,V&gt;,这将让您获得桶数和各个桶的内容.但是,您的代码将是不可移植的,因为它会破坏库类的封装。

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 2019-05-08
      • 2013-09-09
      • 2015-01-11
      • 2013-05-05
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2017-07-13
      相关资源
      最近更新 更多