我正在尝试读取一大段文本并存储每个唯一的单词及其在文本中出现的次数。为此,我创建了一个 Word 类的数组列表。 Word 类只存储单词和它出现的次数。为了避免同一单词的重复,我使用 .contains() 函数来查看我之前是否已经处理过一个单词,但由于某种原因,.contains() 不起作用。
class Main
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("poe.text");
Scanner f = new Scanner(file);
ArrayList<Word> words = new ArrayList<Word>();
int total = 0;
while(f.hasNext())
{
Word temp = new Word(f.next().toLowerCase().trim());
//System.out.println("temp is "+temp.getWord());
total++;
if(words.contains(temp))
{
words.get(words.indexOf(temp)).up();
} else
{
words.add(temp);
}
}
for(Word w:words)
{
System.out.println(w.toString());
}
}
}
if 语句的计算结果永远不会为 true,并且每个单词都会添加到单词 ArrayList 中,即使它已经存在。
最佳答案
在 List 的 Javadoc 中,contains 方法使用 equals() 方法来评估两个对象是否相同。你在你的单词类中实现了 equals 和 hashcode 吗?
Java文档 http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains%28java.lang.Object%29
关于java - 为什么我的 contains 函数没有检测到该元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60946849/