0

我的排序方法出错。

比较法违反其总合同

这是我使用排序方法的排序对象

public abstract class ComparablePerson extends IDValueItem implements
        Comparable<ComparablePerson> {

    private int score;
    private String itemID,itemName;

    //setters and getters

    public int compareTo(ComparablePerson 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 ComparablePerson other = (ComparablePerson) o; 

    if (score == other.getScore() && this.getItemName().equalsIgnoreCase(other.getItemName())) 
        return true; 
    else 
        return false; 
}

我只是调用 Collections.sort(ComparablePersonCollection);

这可能是什么原因?

4

2 回答 2

2

compareToand方法的equals实现似乎不一致,错误告诉您对于相同的两个对象equals给出 truecompareTo而不产生零,这是不正确的。我建议您调用compareTofromequals以确保一致性或以其他方式定义自定义Comparator<T>.

只需这样做:

public abstract class ComparablePerson extends IDValueItem implements Comparable<ComparablePerson> {

    private int score;
    private String itemID,itemName;

    //setters and getters

    public int compareTo(ComparablePerson 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) {
        return compareTo(o) == 0; 
    }   
}
于 2012-12-07T13:04:46.877 回答
1

ComparablePerson 是抽象的,比较方法可能在其他地方重载...

您可以发布客户(拥有该集合)和具体类吗?

此代码运行良好:

public class ComparablePerson implements Comparable< ComparablePerson > {
   public ComparablePerson( int score, String name ) {
      _score    = score;
      _itemName = name;
   }

   @Override public int compareTo( ComparablePerson another ) {
      int delta = _score - another._score;
      if( delta != 0 ) return delta;
      return _itemName.compareToIgnoreCase( another._itemName );
   }

   @Override public boolean equals( Object o ) {
      return 0 == compareTo((ComparablePerson)o);
   }

   @Override public int hashCode() {
      return super.hashCode();
   }

   private final int    _score;
   private final String _itemName;

   public static void main( String[] args ) {
      List< ComparablePerson > oSet = new LinkedList<>();
      oSet.add( new ComparablePerson( 5, "x" ));
      oSet.add( new ComparablePerson( 5, "y" ));
      oSet.add( new ComparablePerson( 5, "z" ));
      oSet.add( new ComparablePerson( 6, "x" ));
      oSet.add( new ComparablePerson( 6, "y" ));
      oSet.add( new ComparablePerson( 6, "z" ));
      Collections.sort( oSet );
      System.err.println( "Ok" );
   }
}
于 2012-12-07T13:14:20.623 回答