While it's true that Collections.unmodifiableList()
works, sometimes you may have a large library having methods already defined to return arrays (e.g. String[]
).
To prevent breaking them, you can actually define auxiliary arrays that will store the values:
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;
}
}
To test:
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()));
Not perfect, but at least you have "pseudo immutable arrays" (from the class perspective) and this will not break related code.
ArrayList
is on par with arrays (since it is implemented internally on top of an array). However, it is generic, thus it is safer to use and more flexible. In most places where an array would be "useful", a collection would be equally useful or better. – Dawsonint[]
andnew int[]
is MUCH easier to type thanList<Integer>
andnew ArrayList<Integer>
? XD – Implantnew ArrayList<>
– DoppJTable
, or something else. At last data in ArrayList are processed in an array-like way to gain performance advantages. So when you are doing simple tasks, why not array? – Debauchery