Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return ArrayList or List?

I'm creating a library to be used by people but why should my method return a List instead of an ArrayList?

Because if the user knows the real type is an ArrayList he will use the accessor [] in a loop instead of iterator but if he doesn't know he will use an iterator.

Same question for LinkedList, if the return type is a List he won't be able to use the correct accessor.

Am I right?

like image 992
kinaesthesia Avatar asked Jul 27 '12 07:07

kinaesthesia


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. 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.

Can you return an ArrayList?

Return an ArrayList From a Static Function in Java A static function can be accessed or invoked without creating an object of the class to which it belongs. If the static method is to be called from outside its parent class, we have to specify the class where that static function was defined.

Why we use ArrayList instead of list?

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.

What is ArrayList return type?

Return Value: int=> Index of the last occurrence of the element in the list. Description: Returns the index of the last occurrence of the specified element o in the list. -1 if the element is not present in the list.


1 Answers

Returning List will make it possible for users of your library to use anything that implements a List interface, while using an ArrayList will force them to use an ArrayList.

If in the future, you as a library creator decide to change your internal implementation, that changes will be hidden from the end user by the generic interface to your library.

like image 140
ipavlic Avatar answered Sep 21 '22 22:09

ipavlic