正如其他人已經正確回答,您需要確保沒有人可以修改listOfNumbers
字段。
但是,您可以使用我編寫的名爲Mutability Detector的自動工具獲得相同的答案,並且當您想測試其他想要使其不變的類時,它可能會派上用場。
鑑於你ExampleClass
,和下面的單元測試:
import org.junit.Test;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;
public class Question_30240358 {
@Test
public void isImmutable() {
assertImmutable(ImmutableClass.class);
}
}
結果是失敗的單元測試,並顯示以下消息:
Expected: org.mutabilitydetector.stackoverflow.ImmutableClass to be IMMUTABLE
but: org.mutabilitydetector.stackoverflow.ImmutableClass is actually NOT_IMMUTABLE
Reasons:
Attempts to wrap mutable collection type using a non-whitelisted unmodifiable wrapper method. [Field: listOfNumbers, Class: org.mutabilitydetector.stackoverflow.ImmutableClass]
Allowed reasons:
None.
at org.mutabilitydetector.unittesting.internal.AssertionReporter.assertThat(AssertionReporter.java:48)
at org.mutabilitydetector.unittesting.MutabilityAsserter.assertImmutable(MutabilityAsserter.java:108)
at org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable(MutabilityAssert.java:672)
at org.mutabilitydetector.stackoverflow.Question_30240358.isImmutable(Question_30240358.java:14)
此測試將通過,如果字段賦值更改爲:
this.listOfNumbers = Collections.unmodifiableList(new ArrayList<Integer>(listOfNumbers));
該測試將捕獲許多其他類型的問題,引入可變性。
'this.listOfNumbers = Collections.unmodifiableList(new ArrayList <>(listOfNumbers));' –
您的列表是可變的。返回一個不可變的版本或一個副本。 – njzk2