3 回答

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

TA貢獻1802條經驗 獲得超10個贊
這個方法在google工具類中也有,源碼內容如下
123 | public static <E> ArrayList<E> newArrayList() { return new ArrayList(); } |
內容是差不多的,唯一的好處就是可以少寫泛型的部分。
這個方法有著豐富的重載:
123 | Lists.newArrayList(E... elements) Lists.newArrayList(Iterable<? extends E> elements) Lists.newArrayList(Iterator<? extends E> elements) |
還有很多前綴擴展方法:
12 | List<T> exactly = Lists.newArrayListWithCapacity( 100 ); List<T> approx = Lists.newArrayListWithExpectedSize( 100 ); |
使得函數名變得更有可讀性,一眼就看出方法的作用。
但是查看源碼發現官方的注解里頭是這么寫的:
Creates a mutable, empty ArrayList instance (for Java 6 and earlier).
創建一個可變的空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及之后版本,本方法已不再有必要,應視之為過時的方法。取而代之你可以直接使用ArrayList的構造器,充分利用鉆石運算符<>(可自動推斷類型)。
添加回答
舉報