title: Example of an immutable class with hashmap
body: <p>I have defined the following classes trying to make "IamImmutable.class" immutable. But when I change hashmap values in TestingImmutability.class after initialising IamImmutable, the changes are applicable to the Hashmap. Hashmap would refer to the same object even if we instantiate it with new HashMap(old). I need to make Hashmap in the instance immutable. I have tried iterating and copying the values as well but that doesn't work. Can anyone suggest on how to proceed?</p>
  
  <pre><code>package string;
  import java.util.HashMap;
  import java.util.Map.Entry;
  
  public final class IamImmutable {
    private int i;
    private String s;
    private HashMap&lt;String, String&gt; h;
  
    public IamImmutable(int i, String s, HashMap&lt;String, String&gt; h) {
      this.i = i;
      this.s = s;
  
      this.h = new HashMap&lt;String, String&gt;();
      for (Entry&lt;String, String&gt; entry: h.entrySet()) {
        this.h.put((entry.getKey()), entry.getValue());
      }
    }
  
    public int getI() {
      return i;
    }
  
    public String getS() {
      return s;
    }
  
    public HashMap&lt;String, String&gt; getH() {
      return h;
    }
  }
  </code></pre>
  
  <p>And a test:</p>
  
  <pre><code>package string;
  
  import java.util.HashMap;
  import java.util.Map.Entry;
  
  public class TestingImmutability {
  
    public static void main(String[] args) {
      int i = 6;
      String s = "!am@John";
      HashMap&lt;String, String&gt; h = new HashMap&lt;String, String&gt;();
  
      h.put("Info1", "!am@John");
      h.put("Inf02", "!amCrazy6");
  
  
      IamImmutable imm = new IamImmutable(i, s, h);
  
      h.put("Inf02", "!amCraxy7");
  
      System.out.println(imm.getS() + imm.getI());
      for (Entry&lt;String, String&gt; entry: h.entrySet())
        System.out.println(entry.getKey() + " --- " + entry.getValue());
    }
  }
  </code></pre>
  
  <blockquote>
    <p>Expected output:</p>
  
  <pre><code>  !am@ John6
  Inf02---!amCrazy6
  Info1---!am@ John
  </code></pre>
    
    <p>Actual output:</p>
  
  <pre><code>  !am@ John6
  Inf02---!amCraxy7
  Info1---!am@ John
  </code></pre>
  </blockquote>