D
D
dearname2017-09-24 03:01:40
Java
dearname, 2017-09-24 03:01:40

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

1 answer(s)
L
longclaps, 2017-09-24
@dearname

...I create an object and add an object with a unique key.
The object has hashCode and equals implemented
, but I will add the user.getKey() key to the map.
Is there anything wrong here?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question