wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt about collection declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about collection declaration" Watch "Doubt about collection declaration" New topic

Doubt about collection declaration

Sekhar Choudary
Ranch Hand

Joined: May 03, 2008
Posts: 57
what is the difference between 1 and 2
1.List<String> L1=new ArrayList<String>();

2.ArrayList<String> L1=new ArrayList<String>();
Ralph Jaus
Ranch Hand

Joined: Apr 27, 2008
Posts: 342
In the second case more methods are available, for example the method ensureCapacity...

In the first case the type of the reference variable L1 is an interface, while in the second case it is a concrete implementation of the interface. Usually the second variant should be choosen. Why ? If you discover that an other implementation would fit better to your requirements (perhaps you need to insert often elements in the middle of the list, then a LinkedList is the better choice), you just have to exchange the implementation (that is you substitute ArrayList on the right in the first example through LinkedList) and you know the rest of the code still works. But if the type of the reference variable changes, that isn't guaranteed in general.

SCJP 5 (98%) - SCBCD 5 (98%)
I agree. Here's the link: http://aspose.com/file-tools
subject: Doubt about collection declaration
It's not a secret anymore!