API java 5 and more: should I return an array or a Collection?

Prefer Collection (or List, or Set as appropriate) to an array. With generics you get the type-checking that was lacking pre-Java 5. Also, by exposing only the interface, you are free to change the implementation later (e.g. switch an ArrayList for a LinkedList).

Arrays and generics don’t mix very well. So, if you want to take advantage of generics, you should usually avoid arrays.
I.e: You can’t generically create an array. For example, if T is a generic type then “new T[0]” doesn’t compile. You’d have to do something like “(T[]) new Object[0]”, which generates an unchecked cast warning. For the same reason, you can’t use generic types with varargs without warnings.

Using Collections.unmodifiableCollection (and similar methods), you get the read-only constraint (which you can’t achieve with an array – you would have to return a clone of the array).

You can’t enforce immutability of members, but then you can’t do that with an array either.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)