title: cloning or unmodifiableCollection
body: <p>During my university classes on Java I learned about the concept of a privacy leak, where a public getter returns a reference to a private mutable object.  </p>
  
  <p>The example they gave was as follows: (Forgive me if the syntax isn't quite right, I'm working from memory)</p>
  
  <pre><code>private HashSet&lt;*&gt; priv = new HashSet&lt;*&gt;
  
  public Collection&lt;*&gt; getPriv () {
      return this.priv;
  }
  </code></pre>
  
  <p>Now the problem with this is the object's client now has the opportunity to corrupt the private HashSet, intentionally or otherwise.  </p>
  
  <p>On the course, the suggested solution was to use the following: </p>
  
  <pre><code>public Collection&lt;*&gt; getPriv () {
      return Collections.unmodifiableCollection (this.priv);
  }
  </code></pre>
  
  <p>This seems like a good solution to me, because not only is the internal state of the object protected from external modification, any attempt to modify the returned unmodifiableCollection will trigger an exception.  The problem with this though, is that it only works with collections.  There doesn't seem to be equivalents for other mutable Java classes.  </p>
  
  <p>Most books on Java I've read since suggest the following: </p>
  
  <pre><code>public Collection&lt;*&gt; getPriv () {
      return this.priv.clone ();
  }
  </code></pre>
  
  <p>This works on any clonable object, but the returned object can be modified to the client object's content.  The internal state of the object is still protected, but now I don't get an exception if I try to modify data that can't really be modified.  This means I could make a mistake where I get the private collection, modify it, and am left mystified as to why my changes aren't reflected in the object, so I've swapped one class of errors (modifying private state) for another (modifying a clone that should be immutable).  </p>
  
  <p>Is there a more generalized way of doing <code>return Collections.unmodifiableCollection (this.priv);</code> that will work with any class (or at least any class that meets some prerequisite such as implementing cloneable), or is my only option to implement mutable and immutable versions of all the private classes I might want to make publicly available through a getter?  </p>