Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...