我想與他們的距離值排序從最小到最大的對象的列表,但好像我犯了一些錯誤Collections.sort不工作
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;
}
}
的文件僅僅是一個鄰接矩陣,其中的價值排-I,COL-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」是什麼?給編譯錯誤..... –
好吧,**長度**只是我從文件中讀取的數組的長度。一切運作良好,除非它看起來像**排序**不起作用 – Forrest
@DươngAnhKhoa它會真的幫助,如果你可以提供一些示例文件 – BackSlash