Possible Duplicate:
Why should the interface for a Java class be prefered?
ArrayList<Integer> al = new ArrayList<Integer>();
List<Integer> l = new ArrayList<Integer>();
what is the difference between these 2 lines? Is there any rules that I should use former one rather than later one in any case? Or vise versa? What is advantage or disadvantage of using particular one?
Thanks.
The first line creates an
ArrayListand stores it in a variable of type ofArrayList, the second line stores it in a variable of typeList.Listis an interface of whichArrayListis an implementation. The rule of thumb for deciding which type to store the instance in (Listor a specific implementation, likeArrayList) is that you should store at the most generalized level suitable for your needs. This means that if you know that the variable must conform to behavior only exhibited byArrayListand not aListin general, then you should useArrayList, otherwise, useList. (This holds forLinkedListor otherListimplementations, too)