我一直在使用Arrays.asList
做一个二维的ArrayList如下:为什么不使用Arrays.asList创建的列表取消装箱值?
ArrayList<List<Integer>> li = new ArrayList<List<Integer>>();
for(int i = 0; i < 100; i++){
li.add(Arrays.asList(1, (int)(Math.random() * 100)));
}
当我尝试的元素如下排序:
Collections.sort(li, new Comparator<List<Integer>>(){
public int compare(List<Integer> l1, List<Integer> l2){
if(l1.get(0) == l2.get(0)){
return l1.get(1) - l2.get(1);
}
return l1.get(0) - l2.get(0);
}
});
中的元素不会被第二正确排序指数。
然而,当我不使用Arrays.asList
,但创建新的ArrayList这样:
ArrayList<List<Integer>> li = new ArrayList<List<Integer>>();
for(int i = 0; i < 100; i++){
ArrayList<Integer> toAdd = new ArrayList<Integer>();
toAdd.add(1);
toAdd.add((int)(Math.random() * 100));
li.add(toAdd);
}
然后排序工作。
我知道Arrays.asList不会复制这些值,而是被原始数组“支持”。但是,get(0)
不应该在比较函数内部自动调用unbox的值吗?
你确定它在第二种情况下工作 - 你确定它不似乎工作,因为随机值使结果似乎排序正确? – luk2302
你确定它在第一种情况下不起作用吗? –
你有没有尝试用'equals'替换'=='在比较器中? – XtremeBaumer