How do I prevent the modification of a private field in a class?

Hossein picture Hossein · Feb 11, 2013 · Viewed 12.9k times · Source

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).

Answer

sp00m picture sp00m · Feb 11, 2013

If you can use a List instead of an array, Collections provides an unmodifiable list:

public List<String> getList() {
    return Collections.unmodifiableList(list);
}