is there's any difference between declaring an arrayList polymorphically like that:
List<Integer> iL = new ArrayList<Integer>();
and the normal style like that:
ArrayList<String> stuff = new ArrayList<String>();
Yes there is a difference
with
List<Integer> iL ;
You could do
iL = new ArrayList<Integer>();
and also
iL = new LinkedList<Integer>();
Advantages:
You could refer to any other Object that is a List
Also See
final List<X> l = new ArrayList<X> then I'm obviously not going to refer to anything else but an ArrayList. Using ArrayList as a public method's param or return value, that is a mortal sin.final on them.It is generally advised to use the first declaration. It allows to change the implementation of the list easily, only by changing the line with the instantiation. Also it shows your intent that you are not using any additional functionality provided by ArrayList.
There is some performance cost when you use the interface, but on modern VMs it should be barely noticeable.
Yes. And it goes beyond just the "coding style" issue the other answers are harping on about...
ArrayList has more methods than the List interface provides (eg trimToSize()), so declaring the variable as an ArrayList gives you access to those methods.
In general, unless you need access to those special methods, it is better to declare it as a List, following the pattern of declaring the abstract class in preference to the concrete (allowing you to swap implementations at will, for example using a LinkedList instead)
There are a few differences when using the interface in the declaration:
LinkedList or CopyOnWriteList) with minimal changes.Given the above, declare method parameter and return types using the interface to hide unimportant implementation details and minimize limitations. Declare local variables using the actual class only when performance is ultra-critical or if you need the additional methods it provides. If you choose a different concrete class later, you'll need to change the call to the constructor which will likely be on the same line as the declaration.