-1

List<String> c = new ArrayList<String>();

I don't understand why they did this,i mean they could have used,

List<String> c=new List<String>(); OR

ArrayList<String> c=new List<String>();

What is the use of this type of syntax and how to use it...

bhavya joshi
  • 1,096
  • 10
  • 20
  • Take a look at [Interfaces](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) – gtgaxiola Apr 09 '15 at 14:21
  • possible duplicate of [How are Java interfaces actually used?](http://stackoverflow.com/questions/504904/how-are-java-interfaces-actually-used) – gtgaxiola Apr 09 '15 at 14:22
  • possible duplicate of [Why should the interface for a Java class be prefered?](http://stackoverflow.com/questions/147468/why-should-the-interface-for-a-java-class-be-prefered) – Ben Win Apr 09 '15 at 14:35

2 Answers2

1

It is actually good that we have a List interface. That way we have the option of using the different type of lists (ArrayList, linkedlist, etc) and inherit the common methods among them.

For example, every list needs to have an add and remove method. But depending on the list, the implementation will vary. An ArrayList will add an item differently than a LinkedList.

So the List interface helps Java coders abstract the common details between lists that will later on have different implementations.

I hope this helps.

Erick
  • 823
  • 16
  • 37
0

You could look at it this way. The interface List provides the common methods every list implementation has, whereas a concrete type like ArrayList provides a specific behaviour on how the list functions.

So List<String> c = new ArrayList<String>(); means a general List of Strings, which has methods like add(), clear() and get() but which acts like an ArrayList.

With using an interface like this you could switch the behaviour of that list at runtime. That means you could do something like this:

List<String> list = new ArrayList<String>();
list = new LinkedList<String>();

That is not possible if you declared list as ArrayList from the beginning.

ArrayList<String> list = new ArrayList<String>();
list = new LinkedList<String>();  

This will generate a compiler-error Type mismatch: cannot convert from LinkedList<String> to ArrayList<String>.

To be more technical, interfaces define sort of a "contract", which means that every class implementing that interface has to provide its defined methods. So if you use an interface, you can be sure that any created object implementing it has the same common methods, since they have to submit to the "contract". But how that object behaves and how the provided methods are implemented is completely up to you.

QBrute
  • 4,405
  • 6
  • 34
  • 40