java - Collections.sort 不起作用

标签 java sorting collections comparable

我想根据对象的距离值对对象列表进行从最小到最大的排序,但我似乎犯了一些错误

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

更新:

现在可以了,问题是我的打印方法

最佳答案

你可以尝试:

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

这将根据 getDistance() 的值以降序方式对列表进行排序。

关于java - Collections.sort 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39037765/

相关文章:

collections - Zorba 系列 : a simple directory of xml files

Python 对字典列表进行排序

java - 在这种情况下,TreeBasedTable.create().rowMap().get(rowKey) 将返回一个空映射

java - 为什么我无法连接到 openfire 服务器?

java - 添加 Android 库 : Only a type can be imported. com.project.test.networktasklibrary 解析为一个包

python - 煎饼排序中最短翻转序列的计数

java - Java中的方法执行顺序排序

java - 找到数组中最接近的值并将其删除

java - 在表单的操作中使用 Servlet 时出现错误的 Servlet 路径

java - SpringBoot 可能存在重定向过滤问题