Tuesday, March 25, 2014

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

No comments:

Post a Comment