gpt4 book ai didi

java - compareTo 错误比较方法违反了它的一般契约

转载 作者:行者123 更新时间:2023-11-30 07:21:59 26 4
gpt4 key购买 nike

我收到以下错误:

Comparison method violates its general contract!

这是我的compareTo方法

public int compareTo(ComparableItem another) {
if (this.score == another.score)
return this.getItemName().compareTo(another.getItemName());
else if ((this.score) > another.score)
return 1;
else
return -1;
}

我想比较项目的分数。但是当分数相同时,我想按名称对它们进行排序。

我需要更改什么以及为什么会出现此错误?

编辑:

score 是一个int,itemname 是一个String

这是 ComparableItem 类:

public abstract class ComparableItem extends MenuListItem implements Comparable<ComparableItem> {

protected int score;

public ComparableItem(String itemID, String itemName) {
super(itemID, itemName);
}

public int compareTo(ComparableItem another) {
if (this.score == another.score)
return this.getItemName().compareTo(another.getItemName());
else if ((this.score) > another.score)
return 1;
else
return -1;
}

public abstract boolean found(String criteria);

这是 MenuListItem 类:

public class MenuListItem {

private String itemID,itemName;

public MenuListItem(String itemID, String itemName){
setItemID(itemID);
setItemName(itemName);
}

public String getItemID() {
return itemID;
}

public void setItemID(String itemID) {
this.itemID = itemID;
}

public String getItemName() {
return itemName;
}

public void setItemName(String itemName) {
this.itemName = itemName;
}

@Override
public String toString() {
return this.itemName;
}

最佳答案

引自 Comparable<T> 的 Java API :

The natural ordering for a class C is said to be consistent with equals if and only if (e1.compareTo((Object)e2) == 0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 of class C.

对于使用 compareTo,api 进一步说明:

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

所以你可能应该重写 equals 以与你的 compareTo() 保持一致, 因为否则两个不同的对象 e1 和 e2 等于 scoregetItemName()会有e1.compareTo((Object)e2) == 0)但不是 e1.equals((Object)e2) .

关于java - compareTo 错误比较方法违反了它的一般契约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13032413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com