• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Lists

 
Raj Joe
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List lst =new ArrayList()
ArrayList lst=new ArrayList()

What is difference b/w the above two statements.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The key is polymorphism. In the first line of code, we can only have access to the methods defined in the List interface. Additional methods defined in ArrayList which implements List, cannot be used by the first line of code.

For e.g.,



HTH.
 
Nigel Browne
Ranch Hand
Posts: 703
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Cheng Wei Lee:
Hi,

The key is polymorphism. In the first line of code, we can only have access to the methods defined in the List interface. Additional methods defined in ArrayList which implements List, cannot be used by the first line of code.



This is not exactly true, in the first line of code we can only access the methods defined in the List interface, unless we explicitly downcast the instance to an ArrayList.
For e.g.


It should be noted however that downcasting is not recommended unless, one is sure that the superclass object is a subclass object.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nigel Browne:
It should be noted however that downcasting is not recommended unless, one is sure that the superclass object is a subclass object.
And you can do that with
 
Raj Joe
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Cheng Wei Lee:
Hi,

The key is polymorphism. In the first line of code, we can only have access to the methods defined in the List interface. Additional methods defined in ArrayList which implements List, cannot be used by the first line of code.

For e.g.,



HTH.



I have seen that people recommend the below style
List listA = new ArrayList();
Is there any advantage?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Raj Joe:

I have seen that people recommend the below style

List listA = new ArrayList();

Is there any advantage?


Yes. It you write code this way, then if you later decide that a LinkedList would work better in your application, then you can just change this one line of code, and everything is guaranteed to still work. In general, using the least specific possible reference types makes your application easier to modify.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic