What is the difference between List and ArrayList?

Ariel Magbanua picture Ariel Magbanua · Feb 15, 2013 · Viewed 293.2k times · Source

I've been using ArrayList recently in my android project at the office and I'm a bit confused between List and ArrayList, what is the difference of the two and what should I use?

Also I saw some implementations of it like.

List<SomeObject> myList = new ArrayList<SomeObject>();

ArrayList<SomeObject> myList = new ArrayList<SomeObject>();

What is the difference of those two instances?

Answer

ATrubka picture ATrubka · Feb 15, 2013

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.