Collections.sort无效

时间:2016-08-19 11:19:51

标签: java sorting collections comparable

我想从最小到最大的对象列表中使用 Distance 值进行排序,但似乎我犯了一些错误

public static ArrayList<ArrayList<Pair>> readInput(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    Scanner in = new Scanner(file);
    int length = Integer.parseInt(in.nextLine());
    ArrayList<ArrayList<Pair>> list = new ArrayList<>();
    while (in.hasNextLine()) {
        ArrayList<Pair> temp = new ArrayList<>();
        String[] s = in.nextLine().split(" ");
        for (int i = 0; i < length; i++) {
            Double distance = Double.parseDouble(s[i]);
            if (distance != 0) {
                temp.add(new Pair(i, distance));
            }
        }
        Collections.sort(temp);
        list.add(temp);
    }
    in.close();
    return list;
}

上课配对

public class Pair implements Comparable<Pair> {
private int index;
private double distance;
public int compareTo(Pair other){
    if (this.getDistance() == other.getDistance())
        return 0;
    else if (this.getDistance() > other.getDistance())
        return 1;
    else
        return -1;
}
public Pair(int index, double distance) {
    super();
    this.index = index;
    this.distance = distance;
}
public int getIndex() {
    return index;
}
public void setIndex(int index) {
    this.index = index;
}
public double getDistance() {
    return distance;
}
public void setDistance(double distance) {
    this.distance = distance;
}

}

文件只是一个邻接矩阵,其中 row-i,col-j 的值是从顶点 i 到的距离顶点 j ,类似于:

4 // first line in the file is the number of vertices
0 1 5 6
4 2 3 1
1 8 9 2
0 0 5 3

这是测试结果

  
      
  • 3.0133 - 2.0321 - 1.0373 - 1.0442 - 1.0488 - 1.0560 - 4.0950 - 1.0246 - 2.0501 - 1.0723 - 1.0285 - 2.0930 - 1.0953 - 1.0528 - 1.0748 - 1.0773 - 2.0731 - 2.0865 - 1.0327 - 1.0611 - 1.0621 - 1.0347 - 2.0688 - 3.014 - 3.055 - 1.0158 - 1.0808 - 1.0111 - 1.0198 - 1.0233
  •   

已更新

它现在正在工作,问题是我的打印方法

1 个答案:

答案 0 :(得分:0)

你可以尝试:

in.close();
return temp.OrderByDescending(x=> x.getDistance())

这将根据getDistance()的值以降序排列列表。