1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.