我正在尝试使用哈希表在数组中找到最常用的词。由于某种原因,while 循环无限循环。我已经调试过,并且该元素从未从它获得的第一个元素开始改变。关于为什么会发生这种情况的任何想法?
这是我的代码:
import java.util.Hashtable;
public class MyClass {
public String mostPopularString (String []words) {
if (words == null)
return null;
if (words.length == 0)
return null;
Hashtable<String, Integer> wordsHash = new Hashtable<String, Integer>();
for (String thisWord : words)
{
if (wordsHash.containsKey(thisWord))
{
wordsHash.put(thisWord, wordsHash.get(thisWord) + 1);
}
else
{
wordsHash.put(thisWord, 1);
}
}
Integer mostPopularCount = 0;
String mostPopularWord = null;
boolean tie = false;
while (wordsHash.keys().hasMoreElements())
{
String currentWord = (String) wordsHash.keys().nextElement();
if (wordsHash.get(currentWord) > mostPopularCount)
{
mostPopularCount = wordsHash.get(currentWord);
mostPopularWord = currentWord;
tie = false;
}
else if (wordsHash.get(currentWord) == mostPopularCount)
{
tie = true;
}
}
if (tie)
return null;
else
return mostPopularWord;
}
}
最佳答案
您正在调用 wordsHash.keys()
在循环的每次迭代中,都会给你一个新的 Enumeration<String>
在每次迭代中 - 然后您将在内部循环中再次调用它。
您想调用它一次,然后遍历单个 Enumeration<String>
:
Enumeration<String> iterator = wordsHash.keys();
while (iterator.hasMoreElements())
{
String currentWord = iterator.nextElement();
...
}
请注意,由于您还获得了每个元素的值,因此最好迭代 entrySet()
而不是 keys()
.
你也最好使用HashMap
而不是 Hashtable
,因为那时你可以只使用增强的 for 循环......
关于java - 无限循环遍历哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14612188/