Pep Skipepep
Pep Skipepep

Reputation: 49

Value changed while nested map in java

I tried to create map (in) inside of the map (out). But, the value of "out" change after I change the "in". This is the example of my code:

      Map<String, LinkedHashMap<String, Integer>> out = new LinkedHashMap<String, LinkedHashMap<String, Integer>>();
      LinkedHashMap<String, Integer> in = new LinkedHashMap<String, Integer>();
      
      in.put("a", 100);
      out.put("u", in);
      System.out.println(out);
      out.put("s", in);
      in.put("b", 500);
      System.out.println(out);

This is the output:

{u={a=100}}
{u={a=100, b=500}, s={a=100, b=500}}

What should I do to get this result:

{u={a=100}}
{u={a=100}, s={a=100}}

Upvotes: 1

Views: 84

Answers (1)

Sergey Afinogenov
Sergey Afinogenov

Reputation: 2212

I only tried to guess what do you exactly want. But if you change inner object then outer object continue reference to the same instance. So, for example, you can create new objects while putting into outer link:

    Map<String, LinkedHashMap<String, Integer>> out = new LinkedHashMap<String, LinkedHashMap<String, Integer>>();
    LinkedHashMap<String, Integer> in = new LinkedHashMap<String, Integer>();

    in.put("a", 100);
    out.put("u", new LinkedHashMap<>(in));
    System.out.println(out);
    out.put("s", new LinkedHashMap<>(in));
    in.put("b", 500);
    System.out.println(out);
    System.out.println(in);

Upvotes: 2

Related Questions