2015-11-05 54 views
1

有没有办法确定我们在HashMap中有哪些存储桶,以及它们包含多少个条目?HashMap存储桶中的条目数

+0

的HashMap - >键集 - > lenght? –

+3

@FranMontero这将让你所有的钥匙,OP是要求水桶 –

+0

@asdfzcx这个链接可以帮助你http://stackoverflow.com/questions/18636576/what-is-meant-by-number-of- bucket-in-the-hashmap – Dev

回答

2

你可以通过反射来做到这一点,但它是非常特殊的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 
+0

谢谢,它在我的情况下工作。 – asdfzcx

2

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

如果你有机会获得你的JDK的源代码,你可以使用反射 API来访问你的HashMap<K,V>,这将让你得到桶数和个体桶的内容private variables。但是,你的代码将是不可移植的,因为它会破坏一个库类的封装。