Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Making <code>immutable</code> return values in java is a matter of <em>either</em> returning already <code>immutable</code> objects types (such as <a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html" rel="noreferrer">String</a>) or returning a <strong>copy</strong> for non-immutable objects.</p> <hr> <p><strong>Sample 1</strong> - Already immutable object</p> <pre><code>public String getValue() { return value; } </code></pre> <p><strong>Sample 2</strong> - Collection of already immutable objects</p> <pre><code>public List&lt;String&gt; getValues() { return new ArrayList&lt;String&gt;(values); } </code></pre> <p><strong>Sample 3</strong> - Non-immutable object</p> <pre><code>public Complex getComplex() { return complex.clone(); } </code></pre> <p><strong>Sample 4</strong> - Collection of non-immutable objects</p> <pre><code>public List&lt;Complex&gt; getComplex() { List&lt;Complex&gt; copy = new ArrayList&lt;Complex&gt;(complexs.size()); for (Complex c : complexs) copy.add(c.clone()); return copy; } </code></pre> <p>Sample 3 and 4 are for conveniance based on that the complex type implements the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Cloneable.html" rel="noreferrer"><code>Cloneable</code></a> interface. </p> <p>Furthermore, to avoid subclasses overriding your immutable methods you can declare them <code>final</code>. As a side note, the <a href="http://javapapers.com/design-patterns/builder-pattern/" rel="noreferrer"><code>builder</code></a> pattern is typically useful for constructing immutable objects. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload