【问题标题】:Comparison method violates its general contract even after checking for null即使在检查 null 之后,比较方法也违反了它的一般合同
【发布时间】:2016-04-01 00:10:42
【问题描述】:

我收到以下错误

无法恢复活动 {com.xxx.yyy.zzz.HomeActivity}:java.lang.IllegalArgumentException:比较方法违反了它的一般合同!

即使出现此错误,我仍在处理字符串的 null 情况。关于可能出错的任何提示。代码如下

public class ConversationComparer implements Comparator<Conversation> {
@Override
public int compare(Conversation x, Conversation y) {

    if (x.getLastMessageDate() == null) {
        return 1;
    }

    if (y.getLastMessageDate() == null) {
        return -1;
    }

    return y.getLastMessageDate().compareTo(x.getLastMessageDate());

}}


public java.util.Date getLastMessageDate() {
        return lastMessageDate;
    }

这就是我使用比较器的方式

if (conversationListAdapter != null) {
            Collections.sort(this.list,new ConversationComparer());
            conversationListAdapter.notifyDataSetChanged();
        }

【问题讨论】:

    标签: java android


    【解决方案1】:

    您还应该再次检查 x 和 y 是否为 null,如果两者都为 null,则返回 0。

    @Override
    public int compare(Conversation x, Conversation y) {
    
       if (x == y || (x != null && y != null && x.getLastMessageDate() == y.getLastMessageDate()))
           return 0;    
    
       if (x == null)
           return 1;
    
       if (y == null)
           return -1;
    
       if (x.getLastMessageDate() == null)
           return 1;
    
       if (y.getLastMessageDate() == null)
           return -1;
    
       return y.getLastMessageDate().compareTo(x.getLastMessageDate());
    }
    

    另外,知道“getLastMessageDate()”返回什么数据类型会很有趣。

    【讨论】:

    • getlastmessage 是 java.util.Date
    • 这不是反对称的。假设x == nully.getLastMessageDate() == null。然后compare(x, y) == 1compare(y, x) == 1 也是。
    • 在这种情况下,我认为您的异常不是来自 compareTo 方法。 Date.compareTo 不会引发 InvalidArgumentException。也许你提供了整个堆栈跟踪。
    • 是的,我认为它现在有效。 +1 麻烦处理x == nully == null
    【解决方案2】:

    我看到的唯一问题是您没有正确处理x.getLastMessageDate()y.getLastMessageDate() 都是null 的情况。

    我认为如果你将这一行添加到它符合合同的方法的开头。

    if (x.getLastMessageDate() == null && y.getLastMessageDate() == null)
        return 0; 
    

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多