aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes List implementation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "List implementation" Watch "List implementation" New topic
Author

List implementation

padmaratna kamble
Greenhorn

Joined: Apr 26, 2006
Posts: 26
hello friends ........
please tell me we always use
List l=new ArrayList();
and Collection c=new ArrayList();

why we not always use

ArrayList a=new ArrayList();
Arno Reper
Ranch Hand

Joined: Mar 14, 2006
Posts: 286
Always...always...its not true, it depends on what you want to do.
arno


The man who makes no mistakes does not usually make anything<br /> <br />>>> SCJP 5.0 >> SCJD B&S <<< In progress
Pavel Kubal
Ranch Hand

Joined: Mar 13, 2004
Posts: 356
Originally posted by padmaratna kamble:
hello friends ........
please tell me we always use
List l=new ArrayList();
and Collection c=new ArrayList();

why we not always use

ArrayList a=new ArrayList();



Imagine situation. You have a class which uses 20 times your once created ArrayList instance. In a newer JVM appears better implementation for List interface and you would like to use it, but you have to rewrite whole class!
If only you had used interface, you could rewrite only one line.

For better design of your api is very, very useful to access classes via their interfaces.
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
It is a basic Object Orientation principle: program to an interface, not to an implementation.

That way you can easily interchange implementations changing just a few lines of code.
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
Look at the following two cases...
Case: 1



In the above code, the instance of ArrayList is referred by ArrayLiist reference variable. Now suppose there is a slight change in ur requirement. Instead of ArrayList u want to use LinkedList, then u have to make changes at two different places in ur code. An ArrayList reference variable can't refer ny LinkedList instances.

U code will become..



Case 2:



change at one place only. Only change ArrayList constructor to LinkedList constructor like this.



This is the obvious advantage with second code.

One more thing in case 2, polymorphic feature of java is used which is not in case 1.

regards

Naseem Khan
[ May 20, 2006: Message edited by: Naseem Khan ]

Asking Smart Questions FAQ - How To Put Your Code In Code Tags
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: List implementation