• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array List Collections  RSS feed

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What is Use of declaring an array list object like
List list = new ArrayList() rather than creating object like
ArrayList arr = new ArrayList();

Thanks.
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first declaration adheres to the generally accepted principle that you should Use Interface References to Collections. You should do this in case you decide later to change to a different kind of List. In that case you'd be guaranteed to only have to change one line of code, your List declaration.

The second declaration is okay if you know that you'll only ever use an ArrayList, but why limit yourself? You might later find out that a LinkedList has better performance characteristics for your particular application. If that happened you'd have to look everywhere in your code that you used an ArrayList reference and see what the change might impact.
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bill,

Thanks for your reply. I have one more question. Say, if I use this,
List list = new ArrayList() do I have to look at the List's methods or ArrayList's methods in the API? Whose methods will I be invoking with the reference variable list?

Thanks.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent question this can be answered if you understand polymorphism a bit check out this and see it you can figure it out yourself
Polymorphism story
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arjun,

If you declare your list as List list = new ArrayList();, then when dealing with your list reference, you'd need to use the List interface. This is not a bad thing! This protects you from using ArrayList-specific methods, which would make it difficult to change your mind later and use a LinkedList.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!