What does this statement with List and ArrayList mean?

后端 未结 5 1688
忘了有多久
忘了有多久 2021-01-14 08:56

I am reading the Drools Planner examples and I came across code like this a lot:

List columnList = new ArrayList(n);
相关标签:
5条回答
  • 2021-01-14 09:12

    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.

    0 讨论(0)
  • 2021-01-14 09:17

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

    0 讨论(0)
  • 2021-01-14 09:22

    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

    0 讨论(0)
  • 2021-01-14 09:26

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

    0 讨论(0)
  • 2021-01-14 09:28

    As a sidenote to the other answers, it's worth noting that List is the compile-time type of columnList and ArrayList is the runtime type.

    0 讨论(0)
提交回复
热议问题