如何验证字符串是否已经在散列表中? java
问题描述:
我有以下情况:我试图循环访问ArrayList
并将每个元素与HashTable
进行比较。如果元素(字符串)相等,我想将其复制到新的HashTable
neu。直到这里进展顺利。 但我想要的是,如果这个单词已经在新的HashTable
neu,不要再重复一遍,并简单地增加一个计数值来表示频率。 我想这个代码从来没有达到else块,因为测试输出它永远不会显示。 我知道,直到contentEquals
它运作良好,它会返回所有相同的单词。如何验证字符串是否已经在散列表中? java
所以:我如何验证字符串是否已经在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());
}
答
我可以管理它!我认为错误确实是从输入的方式,没有重复的地方,因此“其他”从来没有达到过!我只是消除了这种情况,并改变了一些结构。 无论如何都要为你付出努力! :)
for (String x : hash.keySet()) {
long neu = hash.get(x);
for (String s : words) {
if (x.equals(s)) {
neuS.add(x);
neuZ.add(neu);
disc = disc + 1;
}
}
}
答
使用containsKey()
方法来检查,如果给定的密钥已经在哈希表。
static Hashtable<String, Long> map = new Hashtable<String, Long>();
public static void main(String[] args)
{
map.put("test", 1l);
System.out.println(map.containsKey("test")); // true
}
对于字符串比较,既可以使用equals(Object)
或equalsIgnoreCase(String)
方法。
所以,你的代码应该是这样的......
for (String s : count.keySet())
{
for (String x : words)
{
if (x.equals(s))
neu.put(s, neu.containsKey(s) ? neu.get(s) + 1 : 1l);
}
}
请确认您words
和count
的内容。这应该是问题,因为你的代码工作正常。
而不是猜测,使用您的调试器,甚至添加代码中的痕迹,** **知道什么是执行和什么不是。 –
为什么你使用'contentEquals(Charsequence)'而不是'equals(Object)'? – Turing85
如果你的代码中的contentEquals是正确的,那么代码对我来说看起来很好。可能是你使用的数据不包含重复这就是为什么“测试”没有打印 – anon