GarudaAiacos
GarudaAiacos

Reputation: 181

Use ArrayList or List in method parameter list

Hi I am wondering if it is better to use list or arrayList as a method parameter?

for example -

public static void calculate(List<T> list) {}

or

public static void calculate(ArrayList<T> list) {}

I was thinking that it was better to use List because it gives you more options to use a linked list or whatever... but if I am wrong could you tell me why ArrayList is better or why List is better?

Thanks

Upvotes: 1

Views: 2876

Answers (2)

Paul Boddington
Paul Boddington

Reputation: 37645

Your method should accept any argument that the method makes sense for.

If your method makes sense for any List, the argument should have type List<?>.

If your method doesn't need to access the items by index, it might be a good idea to allow the method to accept a Collection<?> or an Iterable<?>.

If your method only makes sense for lists of numbers, the argument should have type List<? extends Number>.

In general, it is not a good idea for a parameter to have type ArrayList. If your method only makes sense for certain types of List, such as Lists that are mutable, or Lists that accept null items, you should make the argument have type List<?> but carefully document the requirements.

Upvotes: 1

ticktock
ticktock

Reputation: 1703

Code to interfaces, code to interfaces, code to interfaces.

What if someone wanted to use your API but pass a different sort of List? Or even not a list at all, but a Collection? Use the most generic interface your API requires.

Upvotes: 1

Related Questions