Note that there are some explanatory texts on larger screens.

plurals
  1. POAPI java 5 and more: should I return an array or a Collection?
    text
    copied!<p>In the spirit of <a href="https://stackoverflow.com/questions/171156/best-practices-always-return-a-never-a">Best Practices: Always return a ____, never a ____</a>, I face a similar question in my upcoming <a href="https://stackoverflow.com/questions/219164/generics-in-legacy-code">migration from JDK1.4.2 to JDK5 and more</a>. (Yes, I <em>know</em>, <a href="http://java.sun.com/products/archive/eol.policy.html" rel="nofollow noreferrer">JDK1.4.2 is EOL!</a> ;-) ).</p> <p>For functions returning a collection (which are not simple <a href="https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property">property collections</a>), I always prefer (in JDK1.4.2) returning an Array instead of a generic List, because:</p> <ul> <li>it enforces the returning type (<code>MyObject[]</code> instead of List of Objects, much more <strong><em>type-safe</em></strong> on a static -- as in 'compilation' -- level)</li> <li>it <em>suggests</em> a 'read-only' character to the returned collection (it is more complicated to add an element to the collection, even though this is not as rigorous as the 'read-only' keyword in c#). This is not the same as saying it is 'immutable' since the references inside the array can still be modified...</li> </ul> <p>Of course, I do always <em>create</em> this returned array (I do not expose any 'internal' array)</p> <p>Now, In JDK5 and more, I could use <code>List&lt;MyObject&gt;</code> if I want to. </p> <p><strong>What are the good reasons for choosing to return <code>MyObject[]</code> instead of List or <code>Collection&lt;MyObject&gt;</code> when coding in java5 ?</strong></p> <p>Bonus, if <code>Collection&lt;MyObject&gt;</code> is used, is it possible to:</p> <ul> <li>enforce a read-only attribute on the returned collection ? (no <code>add()</code> or <code>remove()</code> possible)</li> <li>enforce an immutable aspect to the returned collection ? (even the references of that collection can not be modified)</li> </ul> <p>PS: The <a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="nofollow noreferrer">JavaGenericFAQ</a> did not quite have that one.</p>
 

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