I am trying to go through a text from a file, get each Word and save it as a Word object in a HashSet but i am alway getting the size 1 for the HashSet,it stores only the first object, i dont know maybe there is some really easy way to do it, or maybe i have made some stupid mistake here are you the code:
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);
}
This can happen if Word
has a broken implementation of hashCode
and equals
: it would seem that all the values added in the HashSet
are the same. Check the implementations of those methods in Word
.
If you use an IDE like Eclipse or IntelliJ, it can generate correct implementations for hashCode
and equals
. I suggest you use that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.