0

I was looking at this old question and its chosen answer.

The chosen answer was originally,

ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);

But was later modified to recommend this instead

List<List<Individual>> group = new ArrayList<List<Individual>>(4);

I didn't see an explanation for this on the page, can someone please explain why the second one is recommended over the first one? (I'm assuming it has to do with polymorphism)

Community
  • 1
  • 1
francium
  • 2,384
  • 3
  • 20
  • 29

1 Answers1

2

This is code to interface. Here you can see the assignment is done to a List interface not the ArrayList class which is implementing the List. ArrayList, LinkedList implements List interface, the same way, you can have your own List implementing Class as well. So, in future if you want to change the implementation in such a way that instead of ArrayList object you want some other List implementation like LinkedList then you can easily modify the code like this -

 List<List<Individual>> group = new ArrayList<List<Individual>>(4); 
 to
 List<List<Individual>> group = new LinkedList<List<Individual>>(4)

This change will have no impact on the other part of your code which uses group variable as for other this is a List object not an Arraylist or LinkedList object. It is not going to break your code and you don't have to waste your time to modify your code to accomodate this change.

Yash P Shah
  • 779
  • 11
  • 15
Saurav
  • 51
  • 2