Answer the question
In order to leave comments, you need to log in
Why is only the last object written to the HashMap?
Hello. I read data from the file, then in a loop I create an object and add an object with a unique key. For some reason, it is added, but in the next iteration, the hashmap is reset and the current object is added. Why is that? The object has hashCode and equals implemented.
The code has been truncated.
HashMap<String, User> map = new HashMap<String, User>();
while ((line = reader.readLine()) != null) {
scanner = new Scanner(line);
scanner.useDelimiter(",");
User user = new User();
if (index_str != 0) {
while(scanner.hasNext()) {
String data = scanner.next();
if (index == 0) {
user.setTableId(Long.parseLong(data));
} else if (index == 2) {
user.setLastName(data);
} else if (index == 3) {
user.setName(data);
} else if (index == 4) {
user.setMiddleName(data);
}
index++;
}
String key = user.getKey();
System.out.println(user.getKey().hashCode());
map.put(key,user);
index = 0;
}
index_str++;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question