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?
package string;
import java.util.HashMap;
import java.util.Map.Entry;
public final class IamImmutable {
private int i;
private String s;
private HashMap<String, String> h;
public IamImmutable(int i, String s, HashMap<String, String> h) {
this.i = i;
this.s = s;
this.h = new HashMap<String, String>();
for (Entry<String, String> entry: h.entrySet()) {
this.h.put((entry.getKey()), entry.getValue());
}
}
public int getI() {
return i;
}
public String getS() {
return s;
}
public HashMap<String, String> getH() {
return h;
}
}
And a test:
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<String, String> h = new HashMap<String, String>();
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<String, String> entry: h.entrySet())
System.out.println(entry.getKey() + " --- " + entry.getValue());
}
}
Expected output:
!am@ John6 Inf02---!amCrazy6 Info1---!am@ John
Actual output:
!am@ John6 Inf02---!amCraxy7 Info1---!am@ John