我无法理解我在下面编写的代码的行为。参见:
Set<String> keys = hashmap.keySet();
Iterator<String> keyiterator = keys.iterator();
while(keyiterator.hasNext()) {
out = "";
String s = keyiterator.next();
ArrayList<String> temp = hashmap.get(s);
out = out + temp.get(0);
for(int i = 1; i < temp.size(); i ++)
{
String s1 = temp.get(i);
s1 = s1.replaceAll("\\[\\[", "");
s1 = s1.replaceAll("\\]\\]", "");
s1 = s1.trim();
System.out.println(s1);
ArrayList<String> temp2 = hashmap.get(s1);
if(temp2 != null) out = out + " " + temp2.get(0);
}
System.out.println(out);
}
注意:
hashmap 的形式是 <String, ArrayList<String>>
ArrayList 在位置 0 处有一个数值。例如,
Key = Doc1 List = 0, Poland, Iceland, Candy
Key = Doc2 List = 1, UK, Yule
Key = Poland List = 2, Doc1, Doc2
Key = Iceland List = 3, Doc1, Poland
每个列表条目至少包含数字条目。
问题:
这ArrayList<String> temp = hashmap.get(s);
返回条目列表。
但是ArrayList<String> temp2 = hashmap.get(s1);
为条目返回 null。换句话说,列表是空的。
问题: 简单的说。为什么?一旦我们剥离了左右方 block (请参阅上面代码的 replaceALL 部分),字符串列表就是哈希表中的键名。我试过这个:
ArrayList<String> temp2 = hashmap.get("poland");
其中“poland”是哈希表的已知文档/关键字。但它什么也没返回。但是,作为完整性检查,如果我输入 ArrayList<String> temp2 = hashmap.get(s);
所以它再次查看我上面使用的键,它可以第二次找到该键值就好了。
有人可以向我解释一下出了什么问题吗?我保证会为任何对我的问题做出有意义回答的人提供代表。
最佳答案
您的问题是您从 ArrayList
对象之一(例如 "Poland"
、"Iceland"
等),然后在 map 中查找以该值作为其键 的条目。但是键是 "Doc1"
、"Doc2"
等等,而不是 "Poland"
和 "Iceland"
.
关于java - 查询 : Why is this hashtable breaking on me?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040271/