我正在尝试对 TokenDoubleCounters(我的自定义对象)的 ArrayList 进行排序。在 TokenDoubleCounter 中,我实现了 equals 和 compareTo,如下所示:
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.382692307692308
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,8.937254901960785
字, 8.937254901960785
字,8.937254901960785
字,8.937254901960785
字,5.460792811839323
字,4.746170542635659
字,4.746170542635659
字,4.746170542635659
字,4.382692307692308
...
我错过了什么?如果您需要更多详细信息,请告诉我。
另外,我应该补充一点,所有条目“word”实际上都是不同长度的字符串,等等,但我认为这不相关。
谢谢您的帮助。