How do I prevent the modification of a private field in a class?
If you can use a List instead of an array, Collections provides an unmodifiable list:
public List<String> getList() {
return Collections.unmodifiableList(list);
}
You must return a copy of your array.
public String[] getArr() {
return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
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. Change
public String [] getArr ()
{
return arr;
}
to:
public String [] getArr ()
{
return arr.clone ();
}
or to
public int getArrLength ()
{
return arr.length;
}
public String getArrElementAt (int index)
{
return arr [index];
}