title: Setter for arrays: public data assigned to private array
body: <p>Related with <a href="https://cwe.mitre.org/data/definitions/496.html" rel="nofollow noreferrer">https://cwe.mitre.org/data/definitions/496.html</a></p>
  
  <p>Googling a bit led me to we shouldn't get/set private arrays directly from public getters/setters. We can work it around by returning a copy of the array from getters instead of the actual array. And for the getters, we can assign our private arrays to the copy of the array received as an argument in the setter.</p>
  
  <p>Now, I understand that if we use getters, the reference to the array is out and could be modified anytime. </p>
  
  <pre><code>private int[] arr = {1,2,3}; 
  public int[] getArray() {
      return arr;
  }
  </code></pre>
  
  <p>Somewhere else where the class is accessible, doing this:</p>
  
  <pre><code>int[] badArray = obj.getArray();
  badArray[0] = 100;
  </code></pre>
  
  <p>modifies the <code>private arr</code>. 
  My question is how else the array could be harmed. That is, if I modify my getter to:</p>
  
  <pre><code>public int[] getArray() {
      return Arrays.copyOf(arr, arr.length);
  }
  </code></pre>
  
  <p>and keep my setter as:</p>
  
  <pre><code>public void setArray(int[] arr) {
      this.arr = arr;
  }
  </code></pre>
  
  <p>How could this be risky for my private array. Please explain with an example.
  Related: <a href="https://stackoverflow.com/questions/6665150/getters-and-setters-for-arrays">Getters and setters for arrays</a></p>