wood burning stoves
The moose likes Java in General and the fly likes Using List interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using List interface" Watch "Using List interface" New topic

Using List interface

Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Hello Everyone,

In many places I have seen developers doing something like this with ArrayList:

If at all I am sure that I need ArrayList only then what is the need of having declared it as a reference of List type?

I understand that there is a coding practice followed as Coding To an Interface, but in above case is that really needed?

Please correct me if I am wrong.

Thanks i n advance.
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63865

It's almost always a good idea to code to the interface, especially if the instance ends up being passed to other methods or returned as a method value. Except for when the instance is created, code should only care that it is a List -- the fact that it is an ArrayList is not needed to be known anywhere else.

[Asking smart questions] [About Bear] [Books by Bear]
Malatesh Karabisti
Ranch Hand

Joined: Jul 28, 2010
Posts: 153

List list = new ArrayList();

Here you are creating new object of ArrayList ok, after your development is done in testing phase if you found that ArraList is performing badly you want to have LinkedList. since List interface is implemeted by both you can easily replace the above code with
List list=new LinkedList();
without breadking any functionality
I agree. Here's the link: http://aspose.com/file-tools
subject: Using List interface
It's not a secret anymore!