What are the List or ArrayList declaration differences in Java?

后端 未结 3 1126
挽巷
挽巷 2020-12-18 20:11

I am new to Java. I want to know the difference between:

List< String > list = new ArrayList<>();

and

ArrayLis         


        
3条回答
  •  感情败类
    2020-12-18 20:37

    The three are somewhat equivalent:

    List list = new ArrayList<>();
    

    In the above, you're declaring a variable that implements the List interface which will contain String elements, and instantiate it with the concrete class ArrayList. Also, you're using Java 7's new diamond syntax, son you don't have to write again String between the <>.

    ArrayList list = new ArrayList();
    

    In the above, you're declaring a variable of the concrete class ArrayList which will contain String elements, and instantiate it with the concrete class ArrayList using the "traditional" syntax which mandates that you specify the String type between the <>.

    ArrayList list = new ArrayList<>();
    

    In the above, you're declaring a variable of the concrete class ArrayList which will contain String elements, and instantiate it with the concrete class ArrayList. Also, you're using Java 7's new diamond syntax, son you don't have to write again String between the <>.

    Be aware that the diamond syntax (<>) will only work in Java 7 and above, for previous versions of Java you're stuck with using the traditional syntax () for instantiating generics.

    The last two forms are completely equivalent; the first form is a bit different since you're specifying that the list variable is of type List and not of type ArrayList - and that's the preferred form, since good object-oriented practices dictate that you should program to an 'interface', not an 'implementation'.

提交回复
热议问题