0

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>();
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    It is not related to JSF. What if you need to use another implementation in the last example, `List list = new LinkedList();`? (You cannot do, for example, `ArrayList list = new LinkedList();` in the last example. You will need to change the application code using the last example) – Tiny Jan 07 '16 at 14:04
  • It's not even specific for Java. Also see http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – Marco13 Jan 07 '16 at 15:40

2 Answers2

0

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.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
0

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.

SKBo
  • 619
  • 4
  • 15