Java 集合巢狀List of List

2021-08-19 03:17:32 字數 1109 閱讀 9422

在leetcode上刷題時,發現有這麼乙個返回值:list< list< integer> > ,竟然不知如何是好,於是好哈研究了一番。

public

static

list

> function

()

/** 方法1 */

list> ret1=new arraylist>();

return ret1;

/** 方法2 */

list> ret2=new arraylist<>();

return ret2;

/** 方法3 */

arraylist> ret3=new arraylist>();

return ret3;

要求返回型別為list< list < integer > >,這裡的list是乙個介面,我們希望返回的,表面上是介面,其實返回的是介面的實現類。

/** error, 無法new, 因為list是介面,無法例項化 */

list> ret=new list>();//error

return ret;

/** 

* error,

* cannot convert from arraylist> to list>

* * 作為編譯器,能知道的資訊:

* 返回值是乙個list表,列表的每一項指向乙個list*

* 作為編譯器,在方法1裡,我可以把arraylist向上造型為list,

* 因為裡面的元素都是list,是相同的,可以完美接受其上的各種操作,

* 所以方法1是能夠接受的。

* * 但下面這樣處理後,得到的是arraylist表,表的每一項指向乙個arraylist* 但每一項我希望處理乙個list<>,你不能給我乙個arrylist<>,

* 萬一我想處理的是linkedlist<>什麼的,不就出問題了

* 所以我不能讓你隨意轉換

*/arraylist> ******** = new arraylist>();

return ********;//error

集合的巢狀

hashmap hm new hashmap hashmaphm1 new hashmap hm1.put 曹操 25 hm1.put 周瑜 20 hashmaphm2 new hashmap hm2.put 賈寶玉 21 hm2.put 林黛玉 18 hm.put 三國 hm1 hm.put 紅樓...

集合,迭代器遍歷集合,巢狀集合

什麼是集合?集合有兩個父介面 collection 和 map collection有兩個子介面 list 和 set list 子介面有兩個常用的實現類arraylist和linkedlist 儲存的資料的方式是有序不唯一的 arraylist其實可以理解為乙個可變長度的陣列,可以通過索引訪問相對...

Java介面巢狀

package lu.nesting import static lu.utils.print.import lu.nesting.a.dimp2 介面可以被實現為private,相同的語法既適用於巢狀介面也適用於巢狀類 好處 a.dimp2只能被其自身使用。你無法說他實現了乙個private介面d...