Imagine that I have this class:
public class Test
{
private String[] arr = new String[]{"1","2"};
public String[] getArr()
{
return arr;
}
}
Now, I have another class that uses the above class:
Test test = new Test();
test.getArr()[0] ="some value!"; //!!!
So this is the problem: I have accessed a private field of a class from outside! How can I prevent this? I mean how can I make this array immutable? Does this mean that with every getter method you can work your way up to access the private field? (I don't want any libraries such as Guava. I just need to know the right way to do this).
You must return a copy of your array.
Modifier
private
protects only field itself from being accessed from other classes, but not the object references by this field. If you need to protect referenced object, just do not give it out. Changeto:
or to
You can also use
ImmutableList
which should be better than the standardunmodifiableList
. The class is part of Guava libraries that was create by Google.Here is the description:
Here is a simple example of how to use it:
You could return a copy of the data. The caller who chooses to change the data will only be changing the copy
The
Collections.unmodifiableList
has already been mentioned - theArrays.asList()
strangely not! My solution would also be to use the list from the outside and wrap the array as follows: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
andCollections.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.at this point of view you should use system array copy: