Tuesday, March 25, 2014
List vs ArrayList
List is an interface and ArrayList is an implementation of the List interface.
The arraylist class has only a few methods in addition to the methods available in the List interface.
There is not much difference in this.
The only difference is, you are creating a reference of the parent interface in the first one and a reference of the class which implements the List (i.e) the ArrayList class in the second.
If u use the first, you will be able to call the methods available in the List interface and you cannot make calls to the new methods available in the ArrayList class. Where as, u are free to use all the methods available in the ArrayList, if u use the second one.
http://www.javabeat.net/difference-between-list-and-arraylist/
List list = new ArrayList or ArrayList list = new ArrayList
- List list = new ArrayList or ArrayList list = new ArrayList
to decouple your code from a specific implementation of the interface
When you write your code like this:
List list = new ArrayList();
the rest of your code only knows that data is of type List, which is preferable because it allows you to switch between different implementations of the List interface with ease.
For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library with a LinkedList.
If your library relies heavily on accessing elements in these lists, then eventually you'll find that you've made a poor design decision;
you'll realize that you should have used an ArrayList (which gives O(1) access time) instead of a LinkedList (which gives O(n) access time).
Assuming you have been programming to an interface, making such a change is easy.
You would simply change the instance of List from,
List list = new LinkedList();
to
List list = new ArrayList();
you have written your code to follow the contract provided by the List interface.
if you had implemented the core of your library using
LinkedList list = new LinkedList()
making such a change wouldn't be as easy, as there is no guarantee that the rest of your code doesn't make use of methods specific to the LinkedList class.
the choice is simply a matter of design
http://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n