简体   繁体   中英

What does this statement with List and ArrayList mean?

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);

List is an interface. You can't create instances of interfaces.

ArrayList is 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 List interface. That's because they all provide implementations for the methods that List defines. Moreover, those implementations are likely mostly different, because and ArrayList works differently than, say, a LinkedList .

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 of ListType and subclasses have.

If you do the preferred assignment shown above, then you can assign anything that implements List to list .

List is an interface. ArrayList is an implementation of List .

You can't do new List<Column>(n) because List simply defines methods that must be implemented.

The idea behind having List = (some implementation) is you can have implementation-agnostic code that behaves according to the contract of an interface. (ie: You could replace ArrayList with LinkedList and it'll just work, though it'll be implemented entirely differently and will obviously have different performance characteristics).

List is an interface and cannot be instantiated, so new List will trigger a compile-time error. You can do ArrayList<Column> columnList = new ArrayList<Column>(n); , but this way you can't easily switch between different List implementations( ArrayList is one of them).

List is actually an interface and therefore can not be instantiated. So in order to use list, you must create an object of its implementation, for example: ArrayList. Read http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html for more information

作为其他答案的旁注,值得注意的是ListcolumnList的编译时类型,而ArrayList是运行时类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM