Java HashSet对象添加

时间:2015-09-27 16:30:50

标签: java

我正在尝试从文件中查看文本,获取每个Word并将其保存为HashSet中的Word对象,但我总是获得HashSet的大小1,它只存储第一个对象,我不知道也许有一些非常简单的方法,或者我在这里犯了一些愚蠢的错误你是代码:

public static void main(String[] args) throws IOException {
    File file = new File("C:\\Users\\Taner\\Desktop\\words.txt");       
    Scanner input = new Scanner(file);
    HashSet<Word> wordHash = new HashSet<>();

     while (input.hasNextLine()) {
         String line = input.nextLine();      
         for (String retval: line.split(" ", 0)){
             wordTree.add(new Word(retval));
         } 
     }
     input.close();
     System.out.println(wordTree);
}

1 个答案:

答案 0 :(得分:0)

如果Word的{​​{1}}和hashCode实施失败,可能会发生这种情况: 似乎equals中添加的所有值都是相同的。 在HashSet

中检查这些方法的实现

如果使用Eclipse或IntelliJ等IDE, 它可以为WordhashCode生成正确的实现。 我建议你使用它。

相关问题