| 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
|
|
|
Please explain more, Mike Stach, about the <> and use of wrappers. Remember many people reading here are not familiar with generics or wrappers.
|
 |
 |
|
|
subject: why can we write List list = new ArrayList();
|
|
|