2014-10-17 85 views
1
import java.util.HashMap; 
import java.util.HashSet; 
import java.util.Map; 
import java.util.Set; 

public static void printNumWordsDiscovered(HashMap<String,Integer> vocab, HashSet<String> dictionary) { 
     HashMap <String,Integer> Combine = new HashMap <String,Integer>(); 
     Iterator iterVoc = vocab.entrySet().iterator(); 
     List<String> Dic = new ArrayList<String>(); 
     int i = 0; 
     double actual = 0.0; 
     double token = 0.0; 
     while(iterVoc.hasNext()){ 
      Map.Entry iterVocE = (Map.Entry)iterVoc.next(); 
      if (dictionary.contains(iterVocE.getKey().toString())){ 

       int Value = (int) iterVocE.getValue(); 
       actual += 1; 
       token += Value; 
       Combine.put(iterVocE.getKey().toString(), Value); 

      } 
     } 
     for(String s: dictionary.KeySet()){ 
      if (Combine.contains(dictionary.get(s).toString())){ 
       System.out.println("Dicovered " + dictionary.get(s) + " (count " + Combine.get(dictionary.get(s)) + ")"); 
      } 
     } 
} 

我想通過HashSet進行迭代,並且得到有關我的.get()方法的錯誤。你如何獲得HashSet中的密鑰?獲取Hashset鍵

+0

哪一行導致錯誤。 – brso05 2014-10-17 17:42:01

回答

0

您可以使用HashSet的迭代器。

Iterator it = dictionary.iterator(); 
String element; 
while (it.hasNext()) { 
    element = (String) it.next(); 
    if (Combine.contains(element)){ 
     System.out.println("Dicovered " + element + " (count " + Combine.get(element) + ")"); 
} 
} 

使用迭代器方法迭代HashSet,該方法返回Iterator。 使用迭代器模式代替:

for(String s: dictionary.KeySet()){ 
      if (Combine.contains(dictionary.get(s).toString())){ 
       System.out.println("Dicovered " + dictionary.get(s) + " (count " + Combine.get(dictionary.get(s)) + ")"); 
      } 
     } 

祝你好運!

1

HashSet由HashMap支持。我想首先提到這一點,因爲manouti所說的不完全正確。 HashSet確實有一個鍵;你只是不明確地知道HashSet之外的密鑰(或者你不把它稱爲密鑰,你把它稱爲HashSet之外的值)。

實際上,內部HashMap中的關鍵字是您在HashSet#add(E)中使用的值。對於HashSet的#添加(E)代碼:

public boolean add(E e) { 
    return map.put(e, PRESENT)==null; 
} 

如果存在的話就是該值的虛擬對象:

private static final Object PRESENT = new Object(); 

你想要做什麼,是叫迭代器的HashSet遍歷所有的鑰匙。根據java.util.HashSet#iterator文檔:

返回此集合中元素的迭代器。元素以特定順序返回。

所以這相當於獲取內部HashMap,獲取HashMap#keySet,然後獲取迭代器。這不是問題,但是這是一個HashSet的內部代碼究竟是如何真正做的:

public Iterator<E> iterator() { 
    return map.keySet().iterator(); 
} 

所以這可能比你要找的,但你的問題多一點解釋: 沒有的HashSet #get函數,沒有HashSet#KeySet函數,沒有HashMap#包含函數,所以我建議您在http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html和HashMap文檔http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html中閱讀HashSet文檔,然後再進一步去任何。如有疑問,請閱讀文檔。在Java中,您可以獲得處理API的獨特優勢,該API的記錄非常詳盡。如果你選擇不使用它,那就浪費了。

爲了從HashSet中「獲取」任何東西,你必須有產生相同hashCode的對象......所以我不確定我是否理解你正在做什麼的邏輯。換句話說,如果你已經有了這個對象,你不需要從HashSet中獲取它。

總之,在過去的6行代碼可以改變這樣:

for(String s: dictionary.iterator()){ 
     if (Combine.containsKey(s)){ 
      System.out.println("Dicovered " + s + " (count " + Combine.get(s) + ")"); 
     } 
    }