【发布时间】:2015-07-11 17:14:32
【问题描述】:
我有以下情况:我正在尝试遍历 ArrayList 并将每个元素与 HashTable 进行比较。如果元素(字符串)相等,我想将其复制到新的HashTable neu 中。直到这里一切顺利。
但我想,如果这个词已经在新的HashTable neu 中,不要再放它,简单地在代表频率的值上加一个计数。
我想在这段代码中永远不会到达 else 块,因为 test 输出它永远不会显示。
我知道在contentEquals 之前它运行良好,它会返回所有相等的单词。
那么:如何验证字符串是否已经在HashTable 中?我希望它不会重复,我已经看到了很多类似的问题,但不知道如何在我的代码中正确使用它。
Hashtable<String, Long> neu = new Hashtable<String, Long>();
ArrayList<String> words = new ArrayList<String>();
Hashtable<String, Long> count = new Hashtable<String, Long>();
// adding input
for (String s : count.keySet()) {
for (String x : words) {
if (x.contentEquals(s)) {
if (!neu.containsKey(s)) {
neu.put(s, (long) 1);
} else {
long p = neu.get(s);
p = p + 1;
neu.put(s, p);
System.out.println("test");
}
}
}
输入如下: 计数:
try {
BufferedReader in = new BufferedReader(new FileReader(
"griechenland_test.txt"));
String str;
while ((str = in.readLine()) != null) {
str = str.toLowerCase(); // convert to lower case
String[] words = str.split("\\s+"); // split the line on
// whitespace, would return
// an array of words
for (String word : words) {
if (word.length() == 0) {
continue;
}
Long occurences = wordcount.get(word);
if (occurences == null) {
occurences = (long) 1;
} else {
occurences++;
}
count.put(word, occurences);
}
}
单词:
BufferedReader br = new BufferedReader(new FileReader("outagain.txt"));
for (String line = br.readLine(); line != null; line = br.readLine()) {
String h[] = line.split(" ");
words.add(h[0].toString());
}
【问题讨论】:
-
不要猜测,而是使用调试器,甚至在代码中添加跟踪,以知道什么被执行,什么没有被执行。
-
为什么你使用
contentEquals(Charsequence)而不是equals(Object)? -
如果您的代码中的 contentEquals 是正确的,那么代码对我来说看起来不错。可能是您使用的数据不包含重复项,这就是“测试”没有被打印出来的原因
-
我认为
containsKey是您问题的答案,并且您已经在使用它。所以我不明白这个问题是关于什么的。 -
请验证您的
words和count的内容。这应该是问题所在,因为您的代码运行良好。