In the spirit of Best Practices: Always return a ____, never a ____, I face a similar question in my upcoming migration from JDK1.4.2 to JDK5 and more. (Yes, I know, JDK1.4.2 is EOL! ;-) ).
For functions returning a collection (which are not simple property collections), I always prefer (in JDK1.4.2) returning an Array instead of a generic List, because:
- it enforces the returning type (MyObject[] instead of List of Objects, much more type-safe on a static -- as in 'compilation' -- level)
- it suggests 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...
Of course, I do always create this returned array (I do not expose any 'internal' array)
Now, In JDK5 and more, I could use List<MyObject> if I want to.
What are the good reasons for choosing to return MyObject[] instead of List or Collection<MyObject> when coding in java5 ?
Bonus, if Collection<MyObject> is used, is it possible to:
- enforce a read-only attribute on the returned collection ? (no add() or remove() possible)
- enforce an immutable aspect to the returned collection ? (even the references of that collection can not be modified)
PS: The JavaGenericFAQ did not quite have that one.