• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
kiran kumar
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain more, Mike Stach, about the <> and use of wrappers. Remember many people reading here are not familiar with generics or wrappers.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!