Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用比较器基于另一个数组排序不工作_Java - Fatal编程技术网

Java 使用比较器基于另一个数组排序不工作

Java 使用比较器基于另一个数组排序不工作,java,Java,我想根据java中的另一个数组对一个数组进行排序。我可以使用Pair数据结构,但直接使用比较器中的另一个数组不工作 /*打包任何内容;//不要放置包名*/ 导入java.util.*; 导入java.lang.*; 导入java.io.*; /*只有当类是公共的时,类的名称才必须是“Main”*/ 表意文字 { 公共静态void main(字符串[]args)引发java.lang.Exception { final int[]l=新的int[]{9,17,39,35,20,18,34,11,2

我想根据java中的另一个数组对一个数组进行排序。我可以使用Pair数据结构,但直接使用比较器中的另一个数组不工作

/*打包任何内容;//不要放置包名*/
导入java.util.*;
导入java.lang.*;
导入java.io.*;
/*只有当类是公共的时,类的名称才必须是“Main”*/
表意文字
{
公共静态void main(字符串[]args)引发java.lang.Exception
{
final int[]l=新的int[]{9,17,39,35,20,18,34,11,2,45,46,15,33,47,10,27};
最终列表n=Arrays.asList(32,39,86,81,64,53,76,40,46,63,88,56,52,50,22,38);
Collections.sort(n,新的Comparator(){
公共整数比较(左整数、右整数){
//System.out.println(n.indexOf(左)+“”+n.indexOf(右));
返回l[n.indexOf(左)]-l[n.indexOf(右)];
}
});
//集合。排序(l);
系统输出println(n);
系统输出打印LN(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);
}
publicstaticvoidmain(字符串[]args)抛出java.lang.Exception
{
final int[]l=新的int[]{9,17,39,35,20,18,34,11,2,45,46,15,33,47,10,27};
最终列表n=Arrays.asList(32,39,86,81,64,53,76,40,46,63,88,56,52,50,22,38);
List listCopy=newarraylist(n);
Collections.sort(n,新的Comparator(){
公共整数比较(左整数、右整数){
返回l[listCopy.indexOf(左)]-l[listCopy.indexOf(右);\注意listCopy.indexOf()
}
});
系统输出println(n);
}