我讀this,雖然其中一個答案是有道理的,但我仍然覺得有什麼不妥,所以我會繼續舉個例子。不可變的類不是如此不可變
假設你有這個類:
public class ClassA {
private List<E> mList;
//Constructor assigns some value to mList...
public List<E> getList() {
return mList;
}
}
這個類被認爲是不變,然而,當我做這樣的事情在另一個類,說ClassB的,事情發生:
public class ClassB {
//variables and constructors....
public void aFunction(ClassA classAObject) {
List<E> anotherList = classAObject.getList();
//play around with the variable anotherList, and though ClassA is immutable, I can change the value of its mList variable.
}
}
現在我知道我可以添加'最終',就像我在上面發佈的鏈接中提到的那樣,但是認真地說,我錯過了關於這個不變概念的東西嗎?我的意思是,爲什麼它不是不可改變的,是有原因的嗎?
如果你想要真正的不可變性,你將不得不返回'mList'作爲一個值,而不是一個參考。 –
私有成員變量,'mList'是不可變的 - 沒有辦法重新指定它指向List的另一個實例。但是,它包含的值可以隨時隨地播放。 – jrahhali