gpt4 book ai didi

java - ArrayList 上的 Collections.sort() 似乎无法正确排序

转载 作者:行者123 更新时间:2023-11-29 06:00:15 24 4
gpt4 key购买 nike

我正在尝试对 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;
}

结果让我有些惊讶,因为它们似乎不符合我要求的顺序:

word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,5.460792811839323
word,4.746170542635659
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,5.460792811839323
word,4.746170542635659
word,4.746170542635659
word,4.746170542635659
word,4.382692307692308
...

我错过了什么?如果您需要更多详细信息,请告诉我。

此外,我应该补充一点,所有条目“word”实际上都是不同长度的字符串等,但我认为这无关紧要。

感谢您的帮助。

最佳答案

试试这个:

public int compareTo(TokenDoubleCounter other) {
int result = Double.compare(count, other.count);
return result != 0 ? result : word.compareTo(other.word);
}

关于java - ArrayList 上的 Collections.sort() 似乎无法正确排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10422074/

24 4 0