Imagine that I have this class:
public class Test
{
private String[] arr = new String[]{\"1\",\"2\"};
public String[] getArr()
{
return arr;
The Collections.unmodifiableList has already been mentioned - the Arrays.asList() strangely not! My solution would also be to use the list from the outside and wrap the array as follows:
String[] arr = new String[]{"1", "2"};
public List getList() {
return Collections.unmodifiableList(Arrays.asList(arr));
}
The problem with copying the array is: if you're doing it every time you access the code and the array is big, you'll create a lot of work for the garbage collector for sure. So the copy is a simple but really bad approach - I'd say "cheap", but memory-expensive! Especially when you're having more than just 2 elements.
If you look at the source code of Arrays.asList and Collections.unmodifiableList there is actually not much created. The first just wraps the array without copying it, the second just wraps the list, making changes to it unavailable.