Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return List or ArrayList?

I find myself agreeing to return an interface instead of a concrete class.

The reason is simple, I want loose coupling.

But will there be other implications or trade offs?

like image 956
Oh Chin Boon Avatar asked Apr 26 '12 07:04

Oh Chin Boon


People also ask

Should I return List or ArrayList Java?

It's best to return the most generic type that's appropriate for your interface. Save this answer. Show activity on this post. For types like List or ArrayList there shouldn't be any complication and you should return List promoting code to an interface.

Is it better to use List or ArrayList?

The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.

Should I return a collection or a List?

It depends on what guarantees you want to provide the user. If the data is sequential such that the order of the elements matter and you are allowing duplicates, then use a list. If order of elements does not matter and duplicates may or may not be allowed, then use a collection.

Why do we use List instead of ArrayList Java?

It's preferable to do this because it makes your code more resilient to changes in the implementation. If for some reason it was decided that a different List implementation should be used, code that was programmed to the List interface would not need to be changed extensively.


1 Answers

It's best to return the most generic type that's appropriate for your interface.

If there's some reason why ArrayList is inherently appropriate for the data you're returning then you should use that. Typically List is fine but you might also consider using Collection if the returned values are inherently unordered:

Diagram of Java collections hierarchy

like image 91
dwurf Avatar answered Oct 01 '22 23:10

dwurf