2016-03-26 7 views
0

List<Integer>からList<Pair<Integer,Integer>>に値を取得することに苦労しています。ペアは、私が囲む私が書いたクラスです。 これを行う方法はありますか?私はちょうど参照をコピーする代わりに深いコピーを作成することをお勧めします。私は、リストから値を取得することがうまく動作すると信じて、問題はlistPairにこの値を挿入することです。Java、リストに値を追加<pair>

ご提案いただきありがとうございます。私にとって

public class Pair<L,R>{ 
    private L key; 
    private R value; 


    public Pair(L key, R value) 
    { 
     this.key = key; 
     this.value = value; 
    } 

    public L getL() {return key;} 
    public R getR() {return value;} 
    public void setL(L key) {this.key = key;} 
    public void setR(R value) {this.value = value;} 
} 

It's how I create list(in main()) which I send to function createMatrix 
List<Integer> numbersCopy = new ArrayList<Integer>(); 

    public static void createMatrix(List<Integer> list,List<List<Pair<Integer,Integer>>> matrix) 
    {  
     Collections.sort(list); //sortuje listę 
     Collections.reverse(list); //odwraca kolejnosc 
     int key = 0; 
     List<Pair<Integer,Integer>> listPair = new ArrayList<Pair<Integer,Integer>>(); 
     for(int i=0;i<list.size();i++) 
     { 
      listPair.setR(i) = list.get(i); //elements of list should be saved to value in Pair<Integer, Integer> 
     } 

} 
+3

try: 'listPair.ad d(新しいペア(i、list.get(i))) ' – Titus

+0

ペアの前半ではどうなると思いますか?整数が不変の場合、なぜあなたは深いコピーが必要だと思いますか?なぜあなたのペアクラスを変更可能にしましたか? –

+0

リストの値を持つグラフを作成しているので、深いコピーが必要でした。値を削除して変更することになります。私はJavaに慣れていませんが、単に参照をコピーすると、リスト>の値に影響します。そして私はペアクラスが変更可能であることが何を意味するのか分かりません。 – ninigi

答えて

0
あなた createMatrix方法を変更

public static void createMatrix(List<Integer> list, List<List<Pair<Integer, Integer>>> matrix) { 
    List<Integer> numbersCopy = new ArrayList<Integer>(); 

    Collections.sort(list); //sortuje listę 
    Collections.reverse(list); //odwraca kolejnosc 
    int key = 0; 
    List<Pair<Integer,Integer>> listPair = new ArrayList<Pair<Integer,Integer>>(); 
    for(int i=0;i<list.size();i++) 
    { 
     listPair.add(new Pair<Integer, Integer>(i, list.get(i))); //elements of list should be saved to value in Pair<Integer, Integer> 
    } 
} 

以下のコードで変更されたラインがlistPair.add(new Pair<Integer, Integer>(i, list.get(i)));

0

である私は、より単純な2つのインナーフィールドでBeanを作成し、

としてそれを置くだと思います
class MyBean{ 
Integer int0 =null; 
Integer int1 =null; 
} 
List<MyBean> datos = new List<MyBean>();