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
...)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…