Why is comparision method violating general contract?

99 Views Asked by At

I can't understand why it's happening on a compareTo method using CompareToBuilder from Apache Commons Lang 3 and how may I solve it?

The class is as follow:

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.builder.CompareToBuilder;

@Data
@EqualsAndHashCode(of = {"segno", "causale", "importi"})
public class SaraReportAggregate implements Comparable<SaraReportAggregate> {

    private final String segno;
    private final String causale;
    private final AggregatoSara importi = new AggregatoSara();

    @Data
    public static class AggregatoSara implements Comparable<AggregatoSara> {

        private long importoTotale;
        private long importoTotaleContanti;
        private long numeroTotaleOperazioni;
        private long numeroTotaleOperazioniContanti;
    
        @Override
        public int compareTo(AggregatoSara other) {
            return new CompareToBuilder()
                    .append(other.importoTotale, this.importoTotale)
                    .append(other.numeroTotaleOperazioni, this.numeroTotaleOperazioni)
                    .append(other.importoTotaleContanti, this.importoTotaleContanti)
                    .append(other.numeroTotaleOperazioniContanti, this.numeroTotaleOperazioniContanti)
                    .toComparison();
        }
    }

    @Override
    public int compareTo(SaraReportAggregate other) {
        return new CompareToBuilder()
                .append(this.importi, other.importi)
                .append(this.causale, other.causale)
                .append(this.segno, other.segno)
                .toComparison();
    }
}

Calling Collections#sort(List) on a list of SaraReportAggregate happened to throw

java.lang.IllegalArgumentException: Comparison method violates its general contract!

What should I do?

0

There are 0 best solutions below