What is the difference between these two initialization of List :
List<Integer> aa = new ArrayList<>();
ArrayList<Integer> aaa = new ArrayList<>();
What is the difference between these two initialization of List :
List<Integer> aa = new ArrayList<>();
ArrayList<Integer> aaa = new ArrayList<>();
The first uses polymorphism to assign an object to a reference variable whose type is the interface List
. This is preferable.
In OOP, it is a good practice to assign objects to variables of the most general superclass or interface. If the calling code needs only the methods defined as part of List
, and not the additional methods defined in ArrayList
, then go with List
.
This gives your code the freedom to switch to a different implementation of List
, some class other than ArrayList
, without breaking any calling code.
This is a basic Java 101 concept that should be mastered sooner rather than later on your Java education.