下面的代码在 Java 6 上运行时会抛出“Java 比较方法违反其一般约定”。但是,在 Java 7 上它不会抛出相同的异常。什么问题?如何修改此代码以在 Java 7 上也抛出异常?
class ComparableScore implements Comparable<ComparableScore> {
private int score;
private String itemName;
int getScore() {
return score;
}
void setScore(int i) {
score = i;
}
String getItemName() {
return itemName;
}
void setItemName(String str) {
itemName = str;
}
public int compareTo(ComparableScore another) {
if (score == another.getScore())
return this.getItemName()
.compareToIgnoreCase(another.getItemName());
else if ((score) > another.getScore())
return 1;
else
return -1;
}
@Override
public boolean equals(Object o) {
final ComparableScore other = (ComparableScore) o;
if (score == other.getScore()
&& this.getItemName().equalsIgnoreCase(other.getItemName()))
return true;
else
return false;
}
}