This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes why can we write List list = new ArrayList(); Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "why can we write List list = new ArrayList();" Watch "why can we write List list = new ArrayList();" New topic
Author

why can we write List list = new ArrayList();

kiran kumar
Greenhorn

Joined: Feb 07, 2005
Posts: 29
Hi I am new to java.

please help out me from the following code?

1) List list = new ArrayList();

2) ArrayList list = new ArrayList();

List is an Interface where as ArrayList is a Class.

so what advantages can we get if we write List list = new ArrayList()
rather than the second statement.
Taariq San
Ranch Hand

Joined: Nov 20, 2007
Posts: 189
Because your variable list refers to an interface, it could be any implementation of List, like a Vector or LinkedList, not just ArrayList.

They all implement the methods in List, so you can have some code that does some operations on any old List you give it like populating etc.

That second line, it can still be treated like a List, it is one, but if you have the method declaration "public void doStuff(ArrayList list)", that method will only accept an ArrayList and not a Vector or LinkedList, as with the first.

This is the big advantage of 1 over 2, being able to treat all sorts of different animals for example in the same way. If they can all move, eat, etc, you generally aren't interested in how they accomplish these things.
Mike Stach
Greenhorn

Joined: Oct 26, 2008
Posts: 8
If you always use the below one:

List<> abc = new ArrayList<>;

you may not be able to take adavantage of the specific implementations that Vector, LinkedList or ArrayList might provide. So when you are exposing your functionalility, it is quite important to use the interface. But inside your method, you might want to use a wrapper to also make use of these implementations accoring to the desired functionality.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32689
    
    4
Please explain more, Mike Stach, about the <> and use of wrappers. Remember many people reading here are not familiar with generics or wrappers.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: why can we write List list = new ArrayList();
 
Similar Threads
Why programming to interface
WOW
basic question about ArrayList
what is this?
collection