2015-11-05 141 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。但是,你的代碼將是不可移植的,因爲它會破壞一個庫類的封裝。

相關問題