Use interface or type for variable definition in java?

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

    Both are deprecated since Java 1.5.

    It should be:

    List list = new ArrayList();
    // or whatever data type you are using in your list
    

    Please read Effective Java by Joshua Bloch, especially these two items:

    • 23: Don't use raw types in new code (this is even available online)
    • 52: Refer to objects by their interfaces

    BTW, if you use Guava, you have a factory method for constructing an ArrayList so you don't have to repeat the type parameter:

    List list = Lists.newArraylist();
    

提交回复
热议问题