tawheed
tawheed

Reputation: 5821

Mutability of Hashmaps in java

I am trying to build a giant HashMap of HashMaps. I ran into problems with mutability where I kept modifying the elements that was already added to the map. I ended using this approach, although it does what it is supposed to to wondering there might be a better way to do this

public class Main {

    public static void main(String[] args) {
        HashMap<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>();
        HashMap<String, String> s = null;

        // process 1
        s = new HashMap<>();
        s.put("foo", "bar");
        s.put("foo1", "bar");
        s.put("foo2", "bar");
        s.put("foo3", "bar");
        map.put("m1", (HashMap<String, String>) s.clone());

        // process 2
        s = new HashMap<>();
        s.put("9", "bar");
        s.put("10", "bar");
        s.put("11", "bar");
        s.put("12", "bar");
        map.put("m2", (HashMap<String, String>) s.clone());

        // process 3
        s = new HashMap<>();
        s.put("99", "bar");
        s.put("103", "bar");
        s.put("112", "bar");
        s.put("121", "bar");
        map.put("m3", (HashMap<String, String>) s.clone());

        for (Map.Entry<String, HashMap<String, String>> entry : map.entrySet()) {
            String key = entry.getKey();
            HashMap<String, String> value = entry.getValue();
            System.out.print("");
            // ...
        }
    }

}

Upvotes: 1

Views: 78

Answers (1)

Adam Arold
Adam Arold

Reputation: 30528

Since you create a new HashMap for each inner reference there is no need to clone it. What you are doing here is simply putting a new object to a reference:

s = new HashMap<>();

So in short each HashMap you create this way will be a different object and the s variable holds a reference to the current one you are working with.

Upvotes: 1

Related Questions