Why everybody uses Polymorphism in Java while using collections.
What is the difference between these initializations.
private List<Order> orderList = new ArrayList<Order>();
private ArrayList<Order> orderList = new ArrayList<Order>();
Why everybody uses Polymorphism in Java while using collections.
What is the difference between these initializations.
private List<Order> orderList = new ArrayList<Order>();
private ArrayList<Order> orderList = new ArrayList<Order>();
In the second form, your orderList
can be treated only as an ArrayList<Order>
or something inheriting from ArrayList<Order>
.
In the first form, your orderList
is treated as a List<Order>
and this is recommended when you only use functionality defined by List<T>
interface. This way the code is more flexible and can be easily refactored (e.g. you realize that you need a LinkedList<T>
instead, you change the initialization and most of the code does not need to be changed).
Also, it is helpful for code refactoring to use interfaces instead of actual types, if possible (e.g. use parameters of type List<T>
instead of ArrayList<T>
), because it allows the caller to change list type without changing anything in the called function.
Using the List
or Collection
interface don't force the orderList
variable in a specific implementation. Your code will run just as always, but if you want to use a LinkedList
, or a HashSet
if the Collection order is not important, you'll be free to do it.
You may not find that very useful if the scope of orderList
is just your method, but it helps a lot when you're using or writing a public method.