what is the difference between these 2 lines? [duplicate]
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 开发者_JAVA百科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 ArrayList
and stores it in a variable of type of ArrayList
, the second line stores it in a variable of type List
.
List
is an interface of which ArrayList
is an implementation. The rule of thumb for deciding which type to store the instance in (List
or a specific implementation, like ArrayList
) 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 by ArrayList
and not a List
in general, then you should use ArrayList
, otherwise, use List
. (This holds for LinkedList
or other List
implementations, too)
The reason why you want to use the second line it's because it's usually better to program to interfaces than to classes, sometimes it's related to good practices to do that and one of the benefits it's that you end up with code that:
It's better to test Can use different implementations It's not coupled to ArrayList
For more information you can take a look at the "Hollywood principle" or the Strategy pattern
精彩评论