This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Doubt about collection declaration
jQuery in Action, 3rd edition