我試圖對TokenDoubleCounters(我的自定義對象)的ArrayList進行排序。在TokenDoubleCounter,我已經實現了平等和的compareTo如下:ArrayList上的Collections.sort()似乎沒有正確排序
public class TokenDoubleCounter implements Comparable<TokenDoubleCounter> {
private String word;
private double count;
public boolean equals(Object o) {
if (o instanceof TokenDoubleCounter) {
TokenDoubleCounter other = (TokenDoubleCounter) o;
if (other.word.equals(this.word) && other.count == this.count)
return true;
}
return false;
}
public int compareTo(TokenDoubleCounter other) {
double result = this.count - other.getCount();
if (result > 0.0)
return 1;
if (result < 0.0)
return -1;
return this.word.compareTo(other.getWord());
}
//rest of class omitted
}
被創建,並在下面的函數調用來分類的這些對象:
public List<TokenDoubleCounter> chiSquareValueAll(int cl, int cl2) {
List<TokenDoubleCounter> list = new ArrayList<TokenDoubleCounter>();
for (String word : map.keySet()) {
//chiSquareValue2 returns a double
list.add(new TokenDoubleCounter(word, chiSquareValue2(cl,cl2,word)));
}
Collections.sort(list, Collections.reverseOrder());
return list;
}
最後,通過這些結果迭代,我寫這些給文件:
public boolean printChiSquare(PrintWriter out, int cl, int cl2) {
for (TokenDoubleCounter tdc : this.chiSquareValueAll(cl,cl2)) {
if (tdc.getCount() > 2.7) {
//getWord() returns string value "word" and getCount() returns double value "count"
out.write(tdc.getWord() + "," + tdc.getCount() + "\n");
}
}
return true;
}
的結果有些令我感到詫異,因爲他們似乎並不在我所要求的順序:
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,5.460792811839323
字,4.746170542635659
字,4.382692307692308
字,4.382692307692308
字,4.382692307692308
字,4.382692307692308
字,4.382692307692308
字,4.382692307692308
字,4.382692 307692308
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,5.460792811839323
字,4.746170542635659
字,4.746170542635659
字,4.746170542635659
字,4.382 692307692308
...
我在想什麼?並讓我知道你是否需要更多細節。
此外,我應該補充說,所有條目「單詞」實際上是不同長度的字符串等,但我認爲這不相關。
感謝您的幫助。
這可能是一些你'count'值是'NaN's。這可能會搞砸你的分揀機。 –
爲什麼不使用'int java.lang.Double.compare(double d1,double d2)'? –
按自然順序排序時,排序是否正確(而不是相反順序)? –