试试这个:
while (contentItr.hasNext()) {
String word = (String) contentItr.next();
if (wordIndex.containsKey(word)) {
LinkedList temp = (LinkedList) w.get(word);
temp.addLast(currentUrl);
} else {
LinkedList temp = new LinkedList();
temp.add(currentUrl);
w.put(word, temp);
}
}
如您所见,问题出在向 Map 添加新元素的行中 - add 方法返回一个布尔值,这就是添加到 Map 的内容。上面的代码解决了这个问题并将您想要的内容添加到 Map - 一个 LinkedList。
顺便说一句,请考虑在您的代码中使用泛型类型,这样可以防止此类错误。我会尝试猜测您代码中的类型(如果需要,调整它们,您明白了),假设您在程序的某处有这些声明:
Map<String, String> wordIndex = new HashMap<String, String>();
Map<String, LinkedList<String>> w = new HashMap<String, LinkedList<String>>();
List<String> content = new ArrayList<String>();
Iterator<String> contentItr = content.iterator();
这样,您的问题中的一段代码就可以安全地编写出来,避免不必要的强制转换和类型错误,就像您遇到的那样:
while (contentItr.hasNext()) {
String word = contentItr.next();
if (wordIndex.containsKey(word)) {
LinkedList<String> temp = w.get(word);
temp.addLast(currentUrl);
} else {
LinkedList<String> temp = new LinkedList<String>();
temp.add(currentUrl);
w.put(word, temp);
}
}
编辑
根据下面的 cmets - 假设您实际上 可以 将 LinkedList 替换为 ArrayList(这对于某些操作可能更快)并且 仅 LinkedList-您正在使用的特定方法是 addLast(它是 add 的同义词),上面的代码可以重写如下,使用接口而不是具体的类以更面向对象的风格容器:
Map<String, String> wordIndex = new HashMap<String, String>();
Map<String, List<String>> w = new HashMap<String, List<String>>();
List<String> content = new ArrayList<String>();
Iterator<String> contentItr = content.iterator();
while (contentItr.hasNext()) {
String word = contentItr.next();
if (wordIndex.containsKey(word)) {
List<String> temp = w.get(word);
temp.add(currentUrl);
} else {
List<String> temp = new ArrayList<String>();
temp.add(currentUrl);
w.put(word, temp);
}
}