Hashmap Values Using Repeat Statements

Asked 1 years ago, Updated 1 years ago, 148 views

Code was written to give the key a value using a repeat statement.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {

    public static void main(String[] args) {        

        Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
        List<String> array = new ArrayList<String>();

        String num[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        for (int i = 1; i <= n; i++) {          
            map.put(i, null);
            for (int j = i - 1; j < num.length; j += n) {

                int key = i;
                array.add(num[j]);
                map.put(key, array);
            }
                array.clear();
        }
        System.out.println(map);

    }

}   

the expected result {1=[1, 4, 7], 2=[2, 5, 8], 3=[3, 6, 9]}

Results of execution {1=[], 2=[], 3=[]}

There is only an empty ArrayList even though the key is different and the value is given. How do I fix this code so that it comes out with the expected result?

java hashmap loops

2022-09-22 18:31

1 Answers

The reason why it doesn't work is simple.

Running array.clear(); clears all arrays.

Since I put it, it doesn't get erased when I clear().

put saves only the reference of the array. In other words, if you clear after put, it will be deleted.

Run List<String>array = new ArrayList<String>(); for each iteration to create a new array.

The map.put(key, array); syntax must also run after the nested for ends.


2022-09-22 18:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.