2013-07-09 54 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你。

相关问题