I am new to Java. I want to know the difference between:
List< String > list = new ArrayList<>();
and
ArrayLis
There are two points to remark here:
1.The new Java 7 diamond operator allows you to instantiate a generic class without specifying the type parameter on both sides. So these two are equivalent:
ArrayList< String > list = new ArrayList(); ArrayList< String > list = new ArrayList<>();
2.The more important point is the difference between the first two instantiations. The second one is clear:
ArrayList< String > list = new ArrayList();
In the first one:
List< String > list = new ArrayList<>();
you are using the fact that ArrayList is a subtype of List and therefore the assignment is valid. However, on the new list object you only have the subset of methods that are included in List (because your object is declared as List after all), but with the implementations present in ArrayList. This is called polymorphism in object-oriented programming and allows you to use a subtype of a class instead of the parent, where the parent is expected, in order to provide various different functionalities.