Tuesday, 25 November 2014

Preventing the modification of a private field in Java

Let's say you have a class like:

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!"; //!!!

Bam! We were able to modify a private field outside of the class. This not what you want! To avoid this situation, you can use of the following solutions:
  1. Either create a defensive copy:
  2. 
    public String[] getArr() {
      return arr == null ? null : Arrays.copyOf(arr, arr.length);
    }
    
    
  3. If you can use a List instead of an array, Collections provides an unmodifiable list:
  4. 
    public List getList() {
        return Collections.unmodifiableList(list);
    }
    
    

1 comment:

  1. Titanium dioxide sunscreen | Tithi-Titanium-Arts.com
    Tithi-Titanium-Arts.com - croc titanium flat iron Tithi-Titanium-Arts.com - Tithi-Titanium-Arts.com - titanium wedding bands for men Tithi-Titanium-Arts.com titanium density - Tithi-Titanium-Arts.com - Tithi-Titanium-Arts.com - Tithi-Titanium-Arts.com ceramic or titanium flat iron - titanium welding Tithi-Titanium-Arts

    ReplyDelete