中级农民
- 积分
- 118
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-3-15
- 最后登录
- 1970-1-1
|
本帖最后由 orca 于 2020-5-18 08:10 编辑
比如,这样去初始化是错的,为什么? List<Integer> a = new List<Integer>();
List 是個 interface, 他沒有 constructor, 所以不能用 new List<Integer>() 來 instantiate 一個新的 List object.
附上 List 的 javadoc: https://docs.oracle.com/javase/8/docs/api/java/util/List.html
如果是错的,为何List<List<Integer>> pathsList = new ArrayList<List<Integer>>(); 是对的?
new ArrayList<List<Integer>>() 沒有問題, 因為你正在 call ArrayList 的 constructor (ArrayList 是一個 concrete class, 有 constructor, 所以這樣寫可行).
在 Java 裡 <> (又稱為 diamond) 裏頭的 "List<Integer>" 是個 parameterized type. 為什麼需要他? 因為舊的 compiler 不夠聰明, 他沒辦法自行 figure out 你想生成的 ArrayList 裡面可以存取的 objects 是什麼 type.
現在新的 Java compiler 變聰明了, 你可以直接省略等號右邊 constructor <> 裡的 parameterized type, 他會依照等號左邊的 type 自行推斷右邊的 type 是哪一種, 這叫做 type inference. 省略過後, 你的代碼就可以這樣寫了: List<List<Integer>> pathsList = new ArrayList<>() 他會直接推斷出你等號右邊的 constructor 是 new ArrayList<List<Integer>>()
這邊有對 <> 的介紹: https://www.baeldung.com/java-diamond-operator
ArrayList<List<Integer>>() 为何不是 ArrayList<ArrayList<Integer>>();
這樣寫其實也對, 上面提到 <> 裡代表的是 parameterized type, 那 new ArrayList<ArrayList<Integer>>() 的意思是告訴 Java compiler 你生成的 ArrayList 只能存取 "ArrayList of Integer" objects 而不是更抽象的任何一種 List 都行.
以下兩種寫法, 哪種比較好?
- List<ArrayList<Integer>> firstList = new ArrayList<ArrayList<Integer>>();
- List<List<Integer>> secondList = new ArrayList<List<Integer>>();
現在網上和新書裡大概會推薦後者, 原因是你的 code 可以更 flexible, 無論是 ArrayList<Integer>, LinkedList<Integer>, 或是其他種 List implementation 都可以被放到 secondList 裡. 而第一種就比較 specific 了, 只能存取 ArrayList<Integer>.
這邊有對為什麼建議用 generics 的介紹: https://docs.oracle.com/javase/tutorial/java/generics/why.html
|
|