Kevin
Kevin

Reputation: 23634

Passing List or ArrayList of objects

List<Kevin> kevin = new ArrayList<Kevin>();

I have an List of Objects of Type Kevin, now does it make any difference on what i am passing to my method?.

void method1(List<Kevin>)

void method2(ArrayList<Kevin>)

It seems that both are working, is there any difference apart from that i would have access to List interface related methods on method1 and array list related methods on method2. I am just not sure whether we need to send List or ArrayList of objects.

Upvotes: 0

Views: 2263

Answers (4)

JB Nizet
JB Nizet

Reputation: 692281

Passing an ArrayList would prevent you (or at least, make it more difficult) to change your mind and use another kind of List later, because method2() would rely on the list to be of type ArrayList, and not simply List.

Among the other List implementations that you could want to pass are LinkedList, CopyOnWriteArrayList, Arrays.asList(), Collections.synchronizedList(), or, often, Collections.unmodifiableList().

The best practice is thus to program on interfaces, and pass a List (or even a Collection or Iterable if calling methods should not even assume it's a List).

For a private method inside the same class, it doesn't matter much. But if the method is part of a public API, then passing an ArrayList could really hurt you at some time.

Upvotes: 1

Chris Thompson
Chris Thompson

Reputation: 35598

In most cases, it doesn't practically matter. An ArrayList IS a List so any functionality you get from a List you will also get from an ArrayList. And I should note, by the same principal, you may not actually get an ArrayList but rather some subclass that inherits from ArrayList (just like if you said List).

That said, it is typically considered best practice to require the most general type you need. So, if you only need methods that List provides, then pass a List object, however, if there is something specific to ArrayList that you require then pass that.

Upvotes: 2

Eyal Schneider
Eyal Schneider

Reputation: 22456

method1 will work fine for other implementations of List as well (e.g. LinkedList), while method2 is stricter and accept only one implementation. In general, try to make your method arguments as general as possible, for re-usability reasons.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1504162

They will both behave the same way. It's generally preferable to code to interfaces where possible, so prefer List<Kevin> (or even Iterable<Kevin> if you just need to iterate over the collection). If your method will only function properly if it's an ArrayList<Kevin>, that's fair enough... but otherwise, it's better not to restrict the caller to force them to pass in an ArrayList.

Upvotes: 3

Related Questions