Use interface or type for variable definition in java?

后端 未结 8 1894
挽巷
挽巷 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:58

    List<T> is interface, where ArrayList<T> is class, and this class implements List<T> interface.

    I would prefer 2nd form, which is more general, ie if you do not use methods specific to ArrayList<T> you can declare its type as interface List<T> type. With 2nd form it will be easier to change implementation from ArrayList<T> to other class that implements List<T> interface.

    EDIT: As many of SO users commented both forms can be arguments to any method that accept List<T> or ArrrayList<T>. But when I declare method I would prefer interface:

     void showAll(List <String> sl) ...
    

    and use:

     void showAllAS(ArrayList <String> sl) ...
    

    only when my method uses method specific to ArrayList<T>, like ensureCapacity().

    Response with information that we should use typed List<T> instead of just List is very good (of course if we do not use ancient Java).

    0 讨论(0)
  • 2020-11-29 06:58

    All these answers are the same recite from some dogma they read somewhere.

    A variable declaration and initialization statement, Type x = new Constructor();, is definitely part of implementation detail. It's not part of a public API (unless it's public final, but List is mutable so that's inappropriate)

    As an implementation detail, who you are trying to fool with your abstractions? It's better to keep the type as specific as possible. Is it an array list or a linked list? Should it be thread safe or not? The choice is important for your implementation, you carefully chose the specific list impl. Then you declare it as a mere List as if it doesn't matter and you don't care?

    The only legitimate reason to declare it as List is I'm too lazy to type. That also covers the argument that if I need to move to another List impl I have one less place to modify.

    This reason is legitimate only when the variable scope is small, and you can see all of its usages from one glance. Otherwise, keep the most specific type, so that its performance and semantic characteristics are manifest across all the code that use the variable.

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