2015-01-04 137 views
-1

我有兩個類MainObject。我需要根據數值按升序對數組中的對象進行排序。我從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; 
} 

}

+9

命名一個類「Object」是一個非常糟糕的主意...... – August

+1

'int result = arr [i] .compareTo(arr [i]);' ....不會那行總是返回0?你是比較相同的索引的數組 –

+0

是否是功課?你的'Object'類已經在Java中實現了:檢查'Integer' – Matthieu

回答

0

如果你要循環一個集合的所有元素,那麼就不要使用固定的值,如5這裏:

System.out.println("List of instances"); 
for (int i = 0; i < 5; i++) { 

改爲使用arr.length

這也適用於這一行:

for (int j = 0; j < 5; j++) { 

5可能是正確的,因爲數組長度爲6和你想要的最後一個索引之前終止,但如果你使用一個更大的陣列這段代碼將打破。使用arr.length - 1而不是5


這條線的陣列元件與本身進行比較:

int result = arr[i].compareTo(arr[i]); 

因此result將總是0。它更改爲:

int result = arr[i].compareTo(arr[j]); 

或:

int result = arr[j].compareTo(arr[i]); 

嘗試這兩種方法,看看它們之間的區別。


在你上面的修復程序,您要比較的指數ij的元素。因此,你應該改變這種代碼:

if (result == -1) { 
    tempVar = arr[j + 1]; 
    arr[j + 1] = arr[i]; 
    arr[i] = tempVar; 
} 

使用的j正確的索引:

if (result == -1) { 
    tempVar = arr[j]; 
    arr[j] = arr[i]; 
    arr[i] = tempVar; 
} 

您當前密碼的ij元素(當然,不是j由於錯誤進行比較,但你的意思是這樣),但由於不同的索引j+1,你交換不同的元素。