2014-06-07 153 views
-2

編輯:添加了一些信息。我有一個對象數組。每個對象都有一個名稱和一個值。我需要按照這些值的降序對對象進行排序,並打印出名稱。我看到這個簡單的解決方案,但似乎無法將其應用到我的問題:http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/基於屬性對對象數組排序

該代碼編譯沒有錯誤,但數組未被排序在所有。我知道這是因爲我知道輸出應該是什麼,即輸出應該是類似var364,var200,var65等,我得到的是var1,var2,var3等。

我試圖去掉不相關的代碼份這裏:

Main類

print(data.preselection()); 

private void print (UnitRow preselectedUnitRow) { 
    out.printf("Variables after preselection: \n"); 
    for (int i=0;i<PRESELECTION_LIMIT;i++) { 
     out.printf("%s, ",preselectedUnitRow.getUnitName(i)); 
    } 
} 

數據集(數據)

private UnitRow data; 

... 

public UnitRow preselection() { 
    UnitRow standardDeviationUnits = new UnitRow(numberOfVariables); 
    for (int i=0;i<numberOfVariables;i++){ 
     Unit unit = new Unit(1,variableNames[i],calculateStandardDeviation(i)); 
     standardDeviationUnits.add(unit); 
    } 
    standardDeviationUnits.sort(); 
    return standardDeviationUnits; 
} 

UnitRow

import java.util.Arrays; 

public class UnitRow { 

    private Unit[] units; 
    private int count; 

    ... 

    public void sort() { 
     Arrays.sort(units); 
    } 
} 

單位

public class Unit implements Comparable<Unit>{ 

    private NumberRow elements; //just a class with an array of doubles 
    private String name; 

    ... 

    @Override 
    public int compareTo(Unit compareUnit) { //getValue returns a single type double number 
     int comparison = (int) (compareUnit.getValue(0) - getValue(0)); 
     return comparison; 
    } 
} 

我假設我實現可比是錯誤的。你能發現問題嗎? 我這樣說是因爲我測試如下:

System.out.println(standardDeviationUnits.getValue(0,0)); 
standardDeviationUnits.sort(); 
System.out.println(standardDeviationUnits.getValue(0,0)); 

,返回的值完全相同。

+0

爲什麼你認爲你的'compareTo'是錯的?你是否遇到編譯時錯誤,或者數組排序不正確? – dasblinkenlight

+0

是忘了提。代碼編譯時沒有錯誤,但數組並未排序(完全沒有)。它似乎好像這種甚至沒有被稱爲。我知道它沒有排序,因爲我知道輸出應該是什麼樣子。 – Dimebag

+0

爲什麼不在單元compareTo中,只是返回getValue(0) - CompareUnit.getValue(0)? –

回答

0

看起來相反的順序

public int compareTo(Unit compareUnit) { 
    if (getValue(0) < compareUnit.getValue(0)) return 1; 
    else if (getValue(0) > compareUnit.getValue(0)) return -1; 
    return 0; 
} 

試試這個。

另請注意,在您的compareTo中,您不必要地寫回2;並寫了3 if而不是1 if-else

+0

嗯嘗試我的原始代碼,但與if-else語句。不起作用。然後也嘗試了你的代碼,結果仍然是一樣的。我會更新主要問題,因爲我似乎在代碼中發現了一個相當不同的問題。我會盡快回復。 – Dimebag

+0

這工作!我承認,又犯了一件毀了一切的錯誤,但你的解決辦法就是這樣。謝謝! – Dimebag

+0

不錯,它工作:) – smttsp

0

如果你想進行排序按名稱:

return compareUnit.name.compareTo(name); 

別的我不知道是什麼屬性你的getValue(0)返回給你,但仍然如果你想排序按的getValue(0) :

return compareUnit.getValue(0)-getValue(0); 
+0

謝謝你的回答。請再次檢查主帖子,我添加了我如何測試並注意到排序不起作用。還補充說getValue返回單個數字類型double。可悲的是,你的解決方案不起作用。我真的不知道發生了什麼問題。 – Dimebag