我正在尝试使用Hashtables在数组中找到最流行的单词.由于某种原因,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;
}
}
Run Code Online (Sandbox Code Playgroud)
你正在调用wordsHash.keys()循环的每次迭代,这给你一个新Enumeration<String>的每次迭代 - 然后你在循环内再次调用它.
你想调用它一次,然后遍历单个Enumeration<String>:
Enumeration<String> iterator = wordsHash.keys();
while (iterator.hasMoreElements())
{
String currentWord = iterator.nextElement();
...
}
Run Code Online (Sandbox Code Playgroud)
请注意,因为您还获得了每个元素的值,所以最好迭代entrySet()而不是迭代keys().
你也可以更好地使用HashMap而不是Hashtable,因为你可以使用增强的for循环...
问题是符合的
while (wordsHash.keys().hasMoreElements())
Run Code Online (Sandbox Code Playgroud)
每次循环时,您都会获得枚举的新副本.您将需要获取一次密钥集,并对其进行迭代.
在这里使用增强的for循环可能更容易
for (Map.Entry<String,Integer> entry : wordsHash.entrySet()) {
String currentWord = entry.getKey();
Integer currentCount = entry.getValue();
//more code here
}
Run Code Online (Sandbox Code Playgroud)
这应该提供您想要的行为,同时更简单,更容易阅读.
问题是无论何时调用wordsHash.keys(),它都会返回一个新的枚举:
while (wordsHash.keys().hasMoreElements()) // <=== HERE
{
String currentWord = (String) wordsHash.keys().nextElement(); // <=== AND HERE
Run Code Online (Sandbox Code Playgroud)
您需要做的是创建一个枚举并在整个循环中使用它.
PS你为什么使用Hashtable而不是HashMap?
| 归档时间: |
|
| 查看次数: |
2604 次 |
| 最近记录: |