![](/img/trans.png)
[英]How do I retrieve particular value from an ArrayList<String> in Spring
[英]How do I retrieve a key of ArrayList<String> from a Hashtable?
我基本上有一个包含ArrayList<String>,Boolean
的HashTable。 我需要从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中的一个键。 我只需要取回身份证。
有人可以帮我解决这个问题吗?
您已声明了原始Iterator
,因此其next()
方法将返回一个没有get
方法的Object
。 它是您的密钥,但它被键入为Object
因为您的Iterator
是原始的(没有泛型类型参数)。
使用从该组键返回的通用Iterator
。
Iterator<ArrayList<String>> it = tableRows.keySet().iterator();
然后it.next()
将返回一个ArrayList<String>
,您可以在其上调用get
。
您必须在Iterator
使用原始类型
Iterator<ArrayList<String>> it = tableRows.keySet().iterator();
对于推荐,永远不要使用可变对象作为键,因为你会有意想不到的行为。
如果对象的hashCode()值可以根据其状态进行更改,那么在使用这些对象作为基于散列的集合中的键时必须小心,以确保在将它们用作散列键时不允许它们的状态发生更改。 所有基于散列的集合都假定对象的散列值在用作集合中的键时不会更改。 如果密钥的哈希代码在集合中发生变化,则可能会出现一些不可预测且令人困惑的后果。 这在实践中通常不是问题 - 通常的做法是使用像List这样的可变对象作为HashTable中的键 。
如果你仍然希望以这种方式使String集合不可修改。
List<String> unmodifiableList = Collections.unmodifiableList(myKeyList);
并使用unmodifiableList
作为密钥。
使用ArrayList<String>
作为Map
的关键是一个非常非常糟糕的主意。 你绝不能使用可变对象作为密钥,如果列表发生任何变化,密钥将无效 - 这是一种设计气味(和臭味)。
作为替代方案,我建议你使用ArrayList
中的字符串串联构建一个不可变的键,或者使用一个用Collections.unmodifiableList()
创建的不可变列表,甚至更好,只使用id
列,它不会任何使用整行作为关键的意义。
无论如何,如果你必须使用ArrayList
作为键,下面的代码将解决问题 - 并且不需要显式使用迭代器,在这种情况下,增强的for
循环是迭代键的更好的替代方法:
for (ArrayList<String> al : tableRows.keySet()) {
IDs.add(al.get(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);
}
希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.