我已經定義了以下嘗試使「IamImmutable.class」不可變的類。但是當初始化IamImmutable後,當我在TestingImmutability.class中更改hashmap值時,這些更改適用於Hashmap。即使我們用新的HashMap(舊)實例化它,HashMap也會引用同一個對象。我需要在實例中使Hashmap不可變。我已經嘗試迭代和複製值,但這不起作用。任何人都可以建議如何進行?帶有散列映射的不可變類的示例
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;
}
}
和測試:
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 = "[email protected]";
HashMap<String, String> h = new HashMap<String, String>();
h.put("Info1", "[email protected]");
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());
}
}
預期輸出:
[email protected] John6 Inf02---!amCrazy6 [email protected] John
實際輸出:
[email protected] John6 Inf02---!amCraxy7 [email protected] John
請參閱:http://stackoverflow.com/questions/9043254/how-to-get-a-immutable-collection-from-java-hashmap – slipperyseal