java - CompareTo 是传递的

标签 java compare comparator compareto

我有一个看起来像这样的 POJO:

public class Pojo implements Comparable<Pojo> {

    private String type;

    private String journalId;

    private Date bookingDate;

    private Long account;

    private String description;

    private BigDecimal debit;

    private BigDecimal credit;

    ....
}

我想对这些 POJO 的列表进行排序。目前我的 compareTo 方法如下所示:

@Override
public int compareTo(EfdisJournal other) {
    int i = this.type.compareTo(other.type);
    if (i != 0)
        return i;
    if (this.bookingDate != null && other.bookingDate != null)
        i = this.bookingDate.compareTo(other.bookingDate);
    if (i != 0)
        return i;
    if (this.journalId != null && other.journalId != null)
        i = this.journalId.compareTo(other.journalId);
    if (i != 0)
        return i;
    return this.account.compareTo(other.account);
}

如果我使用此 compareTo 方法运行排序,则会收到此 java.lang.IllegalArgumentException:比较方法违反其一般契约 错误。我用谷歌搜索了一下,我认为发生这种情况是因为某些字段在比较时为 null 。但我不知道如何解决这个问题,也不知道我是否正确为什么会出现该错误。

比较应该这样进行:第一次按 type 比较,然后按 bookingDate 比较,第三次按 journalId 比较,最后比较通过帐户。所有比较都应该是升序的。

  • type 永远不会为 null
  • bookingDate 可能为空
  • journalId 可能为 null
  • 帐户永远不会为空
<小时/>

编辑:

遗憾的是我无法实现该方法,因此顺序是根据需要的。然而,我解决了我遇到的问题,因为存储过程产生了两个结果集,其中第二个结果集是根据需要排序的,所以我唯一要做的就是使用第二个结果集而不是第一个结果集。

最佳答案

您需要处理一个实例具有空bookingDate,而另一个实例具有非空bookingDate的情况。 您应该决定是否应将具有 null bookingDate 的内容排序在具有非 null bookingDate 的内容之前或之后,并适本地编写您的compareTo。 (然后还有 journalId。)然后您可以获得一致排序的顺序。

例如:

@Override
public int compareTo(EfdisJournal other) {
    int i = this.type.compareTo(other.type);
    if (i != 0) {
        return i;
    }
    if ((this.bookingDate==null) ^ (other.bookingDate==null)) {
        return (this.bookingDate==null ? -1 : 1);
    }
    if (this.bookingDate != null && other.bookingDate != null) {
        i = this.bookingDate.compareTo(other.bookingDate);
    }
    if (i != 0) {
        return i;
    }
    if ((this.journalId==null) ^ (other.journalId==null)) {
        return (this.journalId==null ? -1 : 1);
    }
    if (this.journalId != null && other.journalId != null) {
        i = this.journalId.compareTo(other.journalId);
    }
    if (i != 0) {
        return i;
    }
    return this.account.compareTo(other.account);
}

关于java - CompareTo 是传递的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46177908/

相关文章:

java - EditText 中没有输出。为什么?

java - 在具有枚举 (EnumType.STRING) 的实体上使用 LIKE 运算符执行 JPA 查询

python - 在 Python 中,有效地确定两个列表是否是彼此的移位副本

Java : Comparable vs Comparator

java - 末尾带有 null 的集合比较器

JavaFX 和回调

java - 怪物对象删除

iphone - NSString 在整个文本中搜索另一个字符串

java - 如何比较任何对象的两个实例并获取 "dirty"字段

java - 使用 Comparators 帮助比较 float 成员变量