java instantiation,Instantiation of List (Java)
動機
今天刷Leetcode時碰到的一道問題(216. Combination Sum III):
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
給出的function signature為:
public List> combinationSum3(int k, int n) {
}
注意此處返回type為List of List
一開始我傻傻中招(Java知識太不扎實),直接用
List> ls = new List>();
來創(chuàng)建ls,結(jié)果報錯:List是interface
這個問題我已多次犯過,每次都不長記性,歸根結(jié)底是自己基礎(chǔ)知識不扎實造成的重復(fù)性錯誤。因此我把本文當作知識點記錄,來加深對Java List interface及其引申類的理解。
1. 如何實例化(instantiate)List?
當一個class A implements(實現(xiàn))了一個interface B,那么A和B就有了is-a的關(guān)系,及我們可以用:此處A應(yīng)為concrete class
B obj = new A();
來實現(xiàn)B的實例化。
注意:A obj = new B()是錯誤的
那么有哪些classes implement了Java List interface呢?參考Oracle提供的documentation,其中比較常用的有:
ArrayList 和 LinkedList
所以實例化時我們可以用:
List ls1 = new ArrayList();
List ls2 = new LinkedList();
注意,ls只可以調(diào)用List所有的函數(shù),而不可以調(diào)用ArrayList或LinkedList中的(List interface沒有定義)的函數(shù)。下面的函數(shù)調(diào)用會引起compiler error:
ls2.addFirst(e);
如果我們想要調(diào)用concrete class A中另外的函數(shù),我們需要類型為A的引用。ArrayList和LinkedList都提供了方便的轉(zhuǎn)換方法:
ArrayList arrayLs = new ArrayList(ls1);
LinkedList linkedLs = new LinkedList(ls2);
若我們想要完成ls2.addFirst(e),我們可以使用:
linkedLs.addFirst(e);
ls2 = linkedLs;
來達到同樣的效果。
2. 如何實例化List of List
在完成了以上的搜索后,再來看如何實例化List>,這里我犯了第二個錯誤:
List> ls = new ArrayList>();
這是錯誤的,引起compiler error:cannot convert ArrayList> to List>
為什么不能用B obj = new A()呢?這里和generic type有關(guān),此處有比較詳細的解釋。總體來說,A和B不是is-a的關(guān)系。
如下才是正確的方法:
List> ls = new ArrayList>();
在這里,List可以出現(xiàn)在右側(cè),因為它是以數(shù)據(jù)類型的形式出現(xiàn),而不是以Constructor的形式出現(xiàn)。
當我們需要進一步在ls中添加List時,只需要根據(jù)1中的例子,來實例化List即可
3. 實現(xiàn)List的類之間的比較(ArrayList, LinkedList, Stack, Vector)
//TODO
最后分享一下本題我的答案:
public class Solution {
public List> combinationSum3(int k, int n) {
List> rtLs = new LinkedList<>();
if(k <=0 || (n / k) < lvl) return rtLs;
if(k == 1 && n >= lvl && n <= 9) {
LinkedList ls = new LinkedList();
ls.add(n);
rtLs.add(ls);
return rtLs;
}
for(int i = lvl; i < 10; i++) {
if(i > n) break;
lvl = i+1;
List> shorterLs = combinationSum3(k-1, n-i);
for(List ls : shorterLs) {
LinkedList als = new LinkedList(ls);
als.addFirst(i);
rtLs.add(als);
}
}
lvl = 1;
return rtLs;
}
private static int lvl = 1;
}
本題容易產(chǎn)生歧義的地方是a unique set of numbers,其中unique比較容易理解,即不可有順序不同數(shù)字相同的重復(fù)解,而set這個條件比較容易被忽略,應(yīng)理解為每個解中的數(shù)字只可出現(xiàn)一次,如[3,3,3]就不是n=3, k=9的解
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的java instantiation,Instantiation of List (Java)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab怎么整合成一个模块,Matl
- 下一篇: java 多线程写缓存,Java多线程_