Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hashmap's values update every time if I put new values & keys in it

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading