I am reading the Drools Planner examples and I came across code like this a lot:
List<Column> columnList = new ArrayList<Column>(n);
As far as I get it, it is supposed to initialize a list of length n which stores the Column datatype.
But what is the deal with having different collection datatypes on either side of the expression?
If ArrayList<Column> type-matches with List<Column>, what makes it different from doing:
List<Column> columnList = new List<Column>(n);
Listis an interface. You can’t create instances of interfaces.ArrayListis a class which implements List, you can create one.An interface just defines behavior. A class that implements and interface implements that behavior.
You will note that if you look at the API, many different classes implement the
Listinterface. That’s because they all provide implementations for the methods thatListdefines. Moreover, those implementations are likely mostly different, because andArrayListworks differently than, say, aLinkedList.It is preferable to use the form
List list = new ListType()because you can change the list implementation later, if you want to, without affecting your code. The reason for this is if you do
ListType list = new ListType()the type of list is
ListType, which only an instance ofListTypeand subclasses have.If you do the preferred assignment shown above, then you can assign anything that implements
Listtolist.