Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

java - What is the difference between declaring List<Integer> vs ArrayList<Integer>?

List<Integer> mylist = new ArrayList<Integer>();

ArrayList<Integer> mylist2 = new ArrayList<Integer>();

I am wondering what is the actual difference between the above two in java collections API. I am new to java collections API. I know that List is an interface that ArrayList class implements.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...