Reputation: 7386
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>();
Upvotes: 3
Views: 216
Reputation: 41510
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.
Upvotes: 3
Reputation: 36532
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.
Upvotes: 1
Reputation: 240870
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
Upvotes: 4
Reputation: 200148
Apart from all these standard answers "program to the interface" etc., writing ArrayList
where you could've written List
is just plain ugly, so you'd better have a reason to do it -- and 99% of the time there won't be any.
Upvotes: 1
Reputation: 424983
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)
Upvotes: 1
Reputation: 38345
Yes. In the second case, stuff
can only ever be an ArrayList. In the first, iL
can be an instance of any class that implements the List
interface.
Upvotes: 2