Use interface or type for variable definition in java?

后端 未结 8 1998
挽巷
挽巷 2020-11-29 05:59
ArrayList aList = new ArrayList();

List aList = new ArrayList();

What\'s the difference between these two and which is better to use and why?

8条回答
  •  伪装坚强ぢ
    2020-11-29 06:47

    List is an Interface, whereas ArrayList is an implementation of that interface.

    The second is better because it means you can change your ArrayList for another implementation of List later without needing to change the rest of your application. You may want to do this for performance reasons, or because of other aspects of the behaviour of the List implementation that you have chosen/will choose.

提交回复
热议问题