Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

collection

 
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
 
Sheriff
Posts: 21759
102
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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.
 
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
Boost this thread!