permaculture playing cards*
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about collection declaration" Watch "Doubt about collection declaration" New topic
Author

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%)
 
jQuery in Action, 2nd edition
 
subject: Doubt about collection declaration