【问题标题】:Collections.sort not workingCollections.sort 不起作用
【发布时间】:2016-12-26 12:56:49
【问题描述】:

我想用它们的 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;
}

}

file 只是一个邻接矩阵,其中 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

更新

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

【问题讨论】:

  • 能否请您发布数据文件?还有... for 循环中的lenght 是什么?给出编译错误.....
  • 好吧,length 只是我从文件中读取的数组的长度。一切正常,除了似乎 sort 不起作用
  • @DươngAnhKhoa 如果你能提供一些示例文件真的很有帮助
  • @nafas Override 只是一个注解,它对代码没有任何作用。
  • 奇怪,我刚试过你的代码,它对我有用......你的输入也是一个例子吗?如果不是,它们与输出有何关系?那么你是如何打印输出的呢?

标签: java sorting collections comparable


【解决方案1】:

你可以试试:

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

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

【讨论】:

  • 问题是关于 Java,而不是 C#。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
相关资源
最近更新 更多