0

What is the difference between these two initialization of List :

List<Integer> aa = new ArrayList<>();
ArrayList<Integer> aaa = new ArrayList<>();
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
AalekhG
  • 361
  • 3
  • 8

1 Answers1

0

Polymorphism

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154