我想根据java中的另一个数组对一个数组进行排序。我可以使用 Pair 数据结构,但直接在比较器中使用另一个数组不起作用。
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final int[] l = new int[]{9, 17, 39, 35, 20, 18, 34, 11, 2, 45, 46, 15, 33, 47, 10, 27};
final List<Integer> n = Arrays.asList(32, 39, 86, 81, 64, 53, 76, 40, 46, 63, 88, 56, 52, 50, 22, 38);
Collections.sort(n, new Comparator<Integer>() {
public int compare(Integer left, Integer right) {
//System.out.println(n.indexOf(left) + " "+n.indexOf(right));
return l[n.indexOf(left)]-l[n.indexOf(right)];
}
});
//Collections.sort(l);
System.out.println(n);
System.out.println(l);
}
}
获取输出 - [50, 88, 63, 81, 38, 86, 39, 32, 76, 56, 64, 53, 40, 52, 46, 22] 预期输出 - [46,32 等] 对应于 [ 2,9 等]
您的问题是当您对列表进行排序时,参考顺序会发生变化。你开始9->32
和17->39
前两个元素。在比较和更改前两个元素后,“映射”可能会发生变化,您将拥有9->39
和17->32
代替下一次迭代。
要解决这个问题,您需要创建列表的副本。然后,在排序时,n
您可以参考该订单的副本。这样的事情应该工作:
public static void main (String[] args) throws java.lang.Exception
{
final int[] l = new int[]{9, 17, 39, 35, 20, 18, 34, 11, 2, 45, 46, 15, 33, 47, 10, 27};
final List<Integer> n = Arrays.asList(32, 39, 86, 81, 64, 53, 76, 40, 46, 63, 88, 56, 52, 50, 22, 38);
List<Integer> listCopy = new ArrayList(n);
Collections.sort(n, new Comparator<Integer>() {
public int compare(Integer left, Integer right) {
return l[listCopy.indexOf(left)]-l[listCopy.indexOf(right)]; \\notice the listCopy.indexOf()
}
});
System.out.println(n);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句