“Comparison method violates its general contract!”

前端 未结 11 2068
梦如初夏
梦如初夏 2020-11-21 06:07

Can someone explain me in simple terms, why does this code throw an exception, \"Comparison method violates its general contract!\", and how do I fix it?

pri         


        
11条回答
  •  伪装坚强ぢ
    2020-11-21 06:40

    In my case I was doing something like the following:

    if (a.someField == null) {
        return 1;
    }
    
    if (b.someField == null) {
        return -1;
    }
    
    if (a.someField.equals(b.someField)) {
        return a.someOtherField.compareTo(b.someOtherField);
    }
    
    return a.someField.compareTo(b.someField);
    

    What I forgot to check was when both a.someField and b.someField are null.

提交回复
热议问题