Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

java - Exception 'Comparison Method Violates Its General Contract!' when comparing two date properties of an object

First of all, I've already looked at the many questions and answers about this exception but most of them are just about comparing simple integers or the same properties. What I have is an object that has two dates, that when one is null I will use the other one to compare, ex of the class:

public class MyClass {
  private LocalDate primaryDate;
  private LocalDate secondaryDate;
  private String Code;
}

the comparison method is:

 private List<MyClass> sortByDates(final List<MyClass> listOfClass) {
    Comparator<MyClass> comparator = ((Comparator<MyClass>) (first, second) -> {
        if (first.getPrimaryDate() == null || second.getPrimaryDate() == null) {
            return first.getSecondaryDate().compareTo(second.getSecondaryDate());
        }
        return first.getPrimaryDate().compareTo(second.getPrimaryDate());
    }).reversed().thenComparing(MyClass::getCodeAsLong);

    return listOfClass.stream()
        .sorted(comparator)
        .collect(Collectors.toList());
}

Obs1: secondaryDate is never null but I have to use the primaryDate as first option to compare, and primaryDate is never less than secondaryDate
Obs2: Code property is saved as a string but don't have any letter, so it can be converted to long

question from:https://stackoverflow.com/questions/65936878/exception-comparison-method-violates-its-general-contract-when-comparing-two

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only problem is how your handle null for primaryDate.
Check the following example:

MyClass primaryDate secondaryDate
A null 1/1/2021
B 1/1/2023 1/1/2022
C 1/1/2024 1/1/2020

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...