2013-07-09 52 views
1

我基本上有一個HashTable包含ArrayList<String>,Boolean。我需要從Hashtable中檢索密鑰。然後我需要從ArrayList<String>獲得第一個值,這是關鍵。如何從Hashtable中檢索ArrayList <String>的密鑰?

我已經試過:

Hashtable<ArrayList<String>,Boolean> tableRows = tableRead(); // returns the Hashtable. 

    ArrayList<String> IDs = new ArrayList<String>();   

    Iterator it = tableRows.keySet().iterator(); 
    while (it.hasNext()) { 
     IDs.add(it.next().get(0));  
    } 

然而,這給了我一個錯誤:cannot find symbol

[javac] symbol: method get(int) 
[javac] location: class Object 

只給一個功能的想法:我基本上是有一個完整的數據庫排在關鍵Hashtable。我只需要取回ID。

有人可以幫我解決這個問題嗎?

+0

哪個符號找不到? –

+0

你的hashTable定義如何? – nachokk

+0

在你的Iterator聲明中放置一個你想要的類型的泛型參數,即。 '迭代器>''。 –

回答

2

您已經申報了原始Iterator,因此其next()方法將返回Object,該方法沒有get方法。這是你的鑰匙,但它的輸入爲Object,因爲你的Iterator是原始的(沒有泛型類型參數)。

使用從該組鍵返回的通用Iterator

Iterator<ArrayList<String>> it = tableRows.keySet().iterator(); 

然後it.next()將返回ArrayList<String>上,您可以撥打get

1

您的Iterator

Iterator<ArrayList<String>> it = tableRows.keySet().iterator();

而對於推薦使用原始類型,從來沒有使用可變對象作爲重點,因爲你會有意外的行爲。

If an object’s hashCode() value can change based on its state, then we must be careful when using such objects as keys in hash-based collections to ensure that we don’t allow their state to change when they are being used as hash keys. All hash-based collections assume that an object’s hash value does not change while it is in use as a key in the collection. If a key’s hash code were to change while it was in a collection, some unpredictable and confusing consequences could follow. This is usually not a problem in practice — it is not common practice to use a mutable object like a List as a key in a HashTable.

如果您仍然希望以這種方式使String集合不可修改。

List<String> unmodifiableList = Collections.unmodifiableList(myKeyList);

,並使用unmodifiableList關鍵。

0

使用ArrayList<String>作爲Map的關鍵是一個非常非常糟糕的主意。一定不要使用可變對象作爲關鍵字,如果列表發生任何變化,關鍵將失效 - 這是一種設計氣味(而且是一種臭味)。

作爲替代方案,我建議你建立與字符串的串聯一個不可改變的關鍵在ArrayList,或使用Collections.unmodifiableList()甚至更​​好創建的不可變列表,只使用id列,它不會使任何意義使用整個行作爲一個關鍵。

無論如何,如果你使用ArrayList爲重點,下面的代碼將解決這個問題 - 而且也沒有必要明確地使用迭代器,增強for循環是迭代的鑰匙一個更好的選擇這種情況下:

for (ArrayList<String> al : tableRows.keySet()) { 
    IDs.add(al.get(0)); 
} 
0

試試這個

ArrayList<String> list = new ArrayList<>(); 
    Hashtable<ArrayList<String>,Boolean> tableRows = new Hashtable<>(); 
    Set<ArrayList<String>> keys = tableRows.keySet(); 
    Iterator<ArrayList<String>> itr = keys.iterator(); 
    while(itr.hasNext()){ 
     itr.next().get(0); 
    } 

希望這willhelp你。

相關問題