Home » Android » java – What is the difference between List and ArrayList?

java – What is the difference between List and ArrayList?

Posted by: admin March 10, 2020 Leave a comment


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?

How to&Answers:

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.