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?
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0