Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want your class to be immutable (i.e. having only <code>final</code> fields and getters) you must be sure that the values you return are immutable as well. You get this for free when returning Strings and built-in primitives, however some extra steps are necessary for other data types:</p> <ul> <li>wrap collections with immutable decorators or defensively copy them before returning from a getter</li> <li>make a copy of <code>Date</code> and <code>Calendar</code></li> <li>Only return immutable objects or defensively <code>clone</code> them. This also applies to objects in collections.</li> </ul> <p>Note that if you defensively copy a collection, the client can view or modify the copy, but this does not affect the original collection:</p> <pre><code>return new ArrayList&lt;Foo&gt;(foos); </code></pre> <p>On the other hand if you wrap the original collection, the client is able to see all the changes that were introduced to the collection after the wrapper was created, but trying to change the contents of the wrapper will result in runtime exception:</p> <pre><code>return Collections.unmodifiableList(foos); </code></pre> <p>The bottom line is: <code>Foo</code> has to be immutable as well, otherwise the collection is immutable, but the client code can still modify <em>members</em> of the collection. So the same rules apply to <code>Foo</code>.</p> <blockquote> <p>If that's the case (and please correct me if I have a gross misconception here), why not declare the data member public and simplify things?</p> </blockquote> <p>Because:</p> <ul> <li>you might wish to store mutable data inside an object and only provide immutable (read-only) <em>view</em> of the data (like wrapping collections)</li> <li>you can change the implementation in the future, get rid of the field and for instance compute the value on the fly.</li> </ul>
    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. 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