3 回答

TA貢獻(xiàn)1876條經(jīng)驗 獲得超6個贊
List是一個接口,而ArrayList 是一個類。
1、ArrayList 繼承并實(shí)現(xiàn)了List。List list = new ArrayList();這句創(chuàng)建了一個ArrayList的對象后把上溯到了List。此時它是一個List對象了,有些ArrayList有但是List沒有的屬性和方法,它就不能再用了。而ArrayList list=new ArrayList;創(chuàng)建一對象則保留了ArrayList的所有屬性。
2、為什么一般都使用 List list = new ArrayList ,而不用 ArrayList alist = new ArrayList呢。問題就在于List有多個實(shí)現(xiàn)類,如 LinkedList或者Vector等等,現(xiàn)在你用的是ArrayList,也許哪一天你需要換成其它的實(shí)現(xiàn)類呢。
3、這時你只要改變這一行就行了:List list = new LinkedList; 其它使用了list地方的代碼根本不需要改動。假設(shè)你開始用 ArrayList alist = new ArrayList,這下你有的改了,特別是如果你使用了 ArrayList特有的方法和屬性。 ,如果沒有特別需求的話,最好使用List list = new LinkedList,便于程序代碼的重構(gòu),這就是面向接口編程的好處。
4、ava的多態(tài),List只是定義了一堆接口,而對于這些接口,有各種各樣的實(shí)現(xiàn),比如ArrayList,LinkedList等等,不同的實(shí)現(xiàn),會有自己不同的特性以及追加自己特有的方法。當(dāng)你僅僅使用List的通用接口方法時,定義成List(也就是面向接口編程)是非常好的習(xí)慣。

TA貢獻(xiàn)1802條經(jīng)驗 獲得超10個贊
這個方法在google工具類中也有,源碼內(nèi)容如下
123 | public static <E> ArrayList<E> newArrayList() { return new ArrayList(); } |
內(nèi)容是差不多的,唯一的好處就是可以少寫泛型的部分。
這個方法有著豐富的重載:
123 | Lists.newArrayList(E... elements) Lists.newArrayList(Iterable<? extends E> elements) Lists.newArrayList(Iterator<? extends E> elements) |
還有很多前綴擴(kuò)展方法:
12 | List<T> exactly = Lists.newArrayListWithCapacity( 100 ); List<T> approx = Lists.newArrayListWithExpectedSize( 100 ); |
使得函數(shù)名變得更有可讀性,一眼就看出方法的作用。
但是查看源碼發(fā)現(xiàn)官方的注解里頭是這么寫的:
Creates a mutable, empty ArrayList instance (for Java 6 and earlier).
創(chuàng)建一個可變的空ArrayList(適用于java 6及之前的版本)
Note for Java 7 and later: this method is now unnecessary and should
be treated as deprecated. Instead, use the ArrayList constructor
directly, taking advantage of the new "diamond" syntax.
針對java 7及之后版本,本方法已不再有必要,應(yīng)視之為過時的方法。取而代之你可以直接使用ArrayList的構(gòu)造器,充分利用鉆石運(yùn)算符<>(可自動推斷類型)。
添加回答
舉報