【发布时间】:2016-03-26 18:28:34
【问题描述】:
我正在努力获取从 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>
}
}
【问题讨论】:
-
试试:
listPair.add(new Pair(i, list.get(i))) -
你预计这对组合的前半部分会是什么?当整数是不可变的时,为什么你认为你需要一个深拷贝?为什么你让你的 Pair 类是可变的?
-
我想要一个深拷贝,因为我正在使用 list
中的值制作一个图表,我将删除并更改它们。我是 Java 新手,但如果我只复制引用,它会影响 list > 中的值。而且我不知道 Pair 类是可变的是什么意思。 -
更重要的是我尝试了这两种方法,但它们都没有正常工作。使用 Titus 的 solutino 时,我收到 注意:czyGraficzny.java 使用未经检查或不安全的操作。注意:使用 -Xlint 重新编译:unchecked for details.
-
为什么不用简单的地图呢? “对”列表(甚至没有相同的类型)只不过是一张地图(带有 Map.Entry 元素)。
标签: java list class collections insert