Java,向列表<pair>添加一个值



我正在努力从List<Integer>List<Pair<Integer,Integer>>获取值。Pair是我写的一门课,随信附上。有什么办法吗?我更喜欢深度复制,而不是只复制参考资料。我相信从列表中获取一个值很好,问题是将这个值插入listPair。

如果有任何建议,我将不胜感激。

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>
        }
}

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)));

对我来说,Map.Entry<K,V>似乎是你想要的实现,而不是你可以直接调用put(K key, V value)函数。

https://docs.oracle.com/javase/7/docs/api/java/util/Map.html

我认为更简单的是创建一个具有2个内部字段的Bean,并将其作为

class MyBean{
Integer int0 =null;
Integer int1 =null;
}
List<MyBean> datos = new List<MyBean>();

最新更新