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...
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...
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.
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 String
s, 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, interface
s 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.