What is the difference between declaring List vs ArrayList?

前端 未结 7 1903
北荒
北荒 2020-12-20 15:41
List mylist = new ArrayList();

ArrayList mylist2 = new ArrayList();

I am wondering wha

相关标签:
7条回答
  • 2020-12-20 16:42

    The List<Integer> version is the interface type - it only allows you to perform the methods declared by the interface, while the ArrayList<Interger> typed variable allows you to do anything that is declared in the ArrayList<Interger> and its supers. (including the List of course).

    However, though it seems "useless" to chose the first - it actually allows you more flexibility - it will help you change your design much easier if you will later decide you want a LinkedList<Interger> (for example) and not an ArrayList<Interger> as the dynamic type.


    Addition:
    Of course it doesn't mean you need to automatically chose the List<Integer> version. If you actually need to use the exact type of ArrayList - you should chose it. A good rule of thumb is to start with the interface version, and change it to the ArrayList<Integer> only if you find yourself straggling to get something you would have done very easily with an ArrayList type (or if you find yourself casting to an ArrayList...)

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