Home > Back-end >  Hashmap's values update every time if I put new values & keys in it
Hashmap's values update every time if I put new values & keys in it

Time:02-08

So the problem is that if I add a new key&value pair to my hashmap it gets updated ,
right now the key is a number like and ID and the value is a list what countains numbers and
every id should have different list but it's broken for some reason.
So I would like to achieve different list values.
There is the code:

HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i  ) {
    asd.add(i);
    if (i % 5 == 0) {
        countrrr  ;
        map22.put(countrrr,asd);
        System.out.println(asd);
        asd.clear();
    }
}
System.out.println(map22);

CodePudding user response:

The source of your problem is that your code currently uses only one List for storing all results (because HashMap.put() doesn't make clones of its arguments.) You need to create a fresh list after storing a result in the HashMap.

Something like this:

HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i  ) {
    asd.add(i);
    if (i % 5 == 0) {
        countrrr  ;
        map22.put(countrrr, asd);
        System.out.println(asd);
        asd = new ArrayList<>();
    }
}
System.out.println(map22);
  •  Tags:  
  • Related