Java 集合。排序不工作
我想用距离值对对象列表从最小到最大进行排序,但似乎我犯了一些错误Java 集合。排序不工作,java,sorting,collections,comparable,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(
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;
}
这是测试结果
- 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.0198-1.0233
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;
}
它正在工作,问题是我的打印方法您可以尝试:
in.close();
return temp.OrderByDescending(x=> x.getDistance())
这将根据getDistance()的值按降序排列列表 您可以尝试:
in.close();
return temp.OrderByDescending(x=> x.getDistance())
这将根据getDistance()的值按降序排列列表 你能把资料贴出来存档吗?也。。。for循环中的
长度是多少?给出编译错误…嗯,长度就是我从文件中读取的数组的长度。每件事都很好,只是看起来不是这样working@D如果你能提供一些例子,那将非常有帮助file@nafas重写只是一个注释,它对代码没有任何作用。奇怪的是,我刚刚尝试了你的代码,它对我有效。。。输入u是否也提供了一个示例?如果不是,它们与输出有什么关系?那么您是如何打印输出的呢?您能为文件发布数据吗?也。。。for循环中的长度是多少?给出编译错误…嗯,长度就是我从文件中读取的数组的长度。每件事都很好,只是看起来不是这样working@D如果你能提供一些例子,那将非常有帮助file@nafas重写只是一个注释,它对代码没有任何作用。奇怪的是,我刚刚尝试了你的代码,它对我有效。。。输入u是否也提供了一个示例?如果不是,它们与输出有什么关系?那么您如何打印输出呢?问题是关于Java,而不是C。问题是关于Java,而不是C。