2016-11-07 60 views
2

列表類型:如何在java中添加一對對列表對象?

List<Pair<Integer, Pair<Integer, Integer>>> listPairOfPair = null; 

我嘗試了這些,但沒有奏效:

listPairOfPair.add(new Pair<Integer, Pair<Integer, Integer>>(1, (2,3)); 

listPairOfPair.add(new Pair<Integer, Pair<Integer, Integer>>(1, Pair.create(2,3))); 
+0

這是一個java類。也許這是新的我不知道。 –

+1

我想它是'android.util.Pair'(https://developer.android.com/reference/android/util/Pair.html)。以下兩種方法適用於我:'listPairOfPair.add(新對>(1,new Pair (2,3)));''和'listPairOfPair.add(new Pair >(4,Pair.create(5,6)));' –

+0

爲什麼你這樣做不起作用?你能再提供五點信息嗎? –

回答

2

讓我們去爲 「簡單」; 「一層一層」的東西:

Pair<Integer, Integer> onePair = new Pair<>(1, 2); // assuming that you are using that android class that has this ctor 

...創建一個單一的對。

Pair<Integer, Pair<Integer, Integer>> pairOfPairs = new Pair<>(3, onePair); 

...創建一對Integer和先前創建的對。

List<Pair<Integer, Pair<Integer, Integer>>> listOfPairedPairs = new ArrayList<>(); 
listOfPairedPairs.add(pairOfPairs); 

...創建列表並添加一個元素。這可以簡化一點,有:

listdOfPairedPairs = Arrays.asList(pairOfPairs, someOtherPair, ...); 

當然,你可以寫的方法,如:

public Pair<Integer, Pair<Integer, Integer>> of(Integer i1, Integer i2, Integer i3) { 
    ... check that uses such code and returns such a paired pair 

,並使用類似:

listdOfPairedPairs = Arrays.asList(of(1,2,3) , of(4,5,6)); 

當然,但,如果你真的使用android.util Pair實現;那麼你最好遵循Nicolas的建議並使用Pair.create()!

+0

@NicolasFilotto感謝您的輸入。我實際上把這個問題誤解爲對列表的列表;而不是雙對的列表。修正了這個;並添加了一些更有用的東西(所以我希望)。並記錄下來:我很高興看到你的聲譽比我更快 - 而且你推翻了我;因爲我幾周前當「你的」代表「追逐」我的代表時,我真的不喜歡這種情況。 – GhostCat

+0

@NicolasFilotto也許我應該說,雖然我希望你在某個時候對你的代表有信心,這樣我纔有機會再次趕上。我的目標是到2020年左右讀100K。那麼,也許不是真的。但如果事情解決......無論如何,你的目標是什麼? – GhostCat

+0

@NicolasFilotto當然,你有一個點。我試圖保持友好(總是看着Jon Skeet做得很平靜*),但是我不得不承認,在看到第50位新手想到「這裏壞的代碼,現在來修復它」之後,有時我會發脾氣也是。那麼祝你好運! – GhostCat

2

假設你使用android.util.Pair,它可以簡單地實現爲下一:

listPairOfPair.add(new Pair<>(1, new Pair<>(2, 3))); 

listPairOfPair.add(Pair.create(1, Pair.create(2, 3))); 

NB:確保Android設備中啓動它,否則你會得到類型錯誤java.lang.RuntimeException: Stub!

相關問題