Mặc dù đúng là như vậy Collections.unmodifiableList(), đôi khi bạn có thể có một thư viện lớn có các phương thức đã được xác định để trả về mảng (ví dụ String[]). Để tránh phá vỡ chúng, bạn thực sự có thể xác định các mảng phụ sẽ lưu trữ các giá trị:
public class Test {
private final String[] original;
private final String[] auxiliary;
/** constructor */
public Test(String[] _values) {
original = new String[_values.length];
// Pre-allocated array.
auxiliary = new String[_values.length];
System.arraycopy(_values, 0, original, 0, _values.length);
}
/** Get array values. */
public String[] getValues() {
// No need to call clone() - we pre-allocated auxiliary.
System.arraycopy(original, 0, auxiliary, 0, original.length);
return auxiliary;
}
}
Để kiểm tra:
Test test = new Test(new String[]{"a", "b", "C"});
System.out.println(Arrays.asList(test.getValues()));
String[] values = test.getValues();
values[0] = "foobar";
// At this point, "foobar" exist in "auxiliary" but since we are
// copying "original" to "auxiliary" for each call, the next line
// will print the original values "a", "b", "c".
System.out.println(Arrays.asList(test.getValues()));
Không hoàn hảo, nhưng ít nhất bạn có "mảng giả bất biến" (theo quan điểm của lớp) và điều này sẽ không phá vỡ mã liên quan.