-1
我有兩個類Main
和Object
。我需要根據數值按升序對數組中的對象進行排序。我從compareTo返回-1,1和0,並且我需要相應地運行for循環來對我的數組進行排序。我不想使用Arrays.sort,我需要手動完成。排序部分n Main
類不起作用。任何幫助都可能有用。謝謝。Java比較對數組排序
public class Main {
public static void main(String[] args) {
Object[] arr = new Object[6];
arr[0] = new Object(2);
arr[1] = new Object(5);
arr[2] = new Object(3);
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);
System.out.println("List of instances");
for (int i = 0; i < 5; i++) {
System.out.println(arr[i].getValue());
}
System.out.println();
Object tempVar;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < 5; j++) {
int result = arr[i].compareTo(arr[i]);
if (result == -1) {
tempVar = arr[j + 1];
arr[j + 1] = arr[i];
arr[i] = tempVar;
}
}
}
System.out.println("List of sorted instances");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].getValue());
}
}
}
public class Object implements Comparable<Object> {
private int value;
public Object(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public int compareTo(Object o) {
int result = 0;
if (this.value > o.getValue()) {
result = 1;
} else if (this.value < o.getValue()) {
result = -1;
} else if (this.value == o.getValue()) {
result = 0;
}
return result;
}
}
命名一個類「Object」是一個非常糟糕的主意...... – August
'int result = arr [i] .compareTo(arr [i]);' ....不會那行總是返回0?你是比較相同的索引的數組 –
是否是功課?你的'Object'類已經在Java中實現了:檢查'Integer' – Matthieu