• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collection

 
sandeep Talari
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why we should prefer,

List list = new ArrayList();

despite

ArrayList list = new ArrayList();
please explain
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to switch to another implementation of List, like Vector or LinkedList, or even a custom one, you need to change only one line of code - the initialization.

If you declare it as ArrayList, you are much more likely to call methods that belong to ArrayList. If you then switch, you will get compile errors about the methods not existing. If you declare it as List you won't get that problem since that set of methods is 100% sure to be implemented.
 
Shrinivas Mujumdar
Ranch Hand
Posts: 328
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

You can take an advantage of Polymorphism in this case.

Keeping your Left Hand Side of an expression generic, you have a flexibility of changing Right Hand Side to any type of list.

e.g. you can still say later on as per changes in requiement

List list=new Vector();

and still make use of all methods in List interface.

Thanks,
Shriniwas
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic