Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does org.apache.commons.lang.builder.CompareToBuilder do?

I learned about the Comparable interface, for which a class must implement compareTo method. A project I am using that method as:

public class EmployeeAssignmentTotal implements Comparable<EmployeeAssignmentTotal>, Serializable {

private Employee employee;
private int total;
....
public int compareTo(EmployeeAssignmentTotal other) {
    return new CompareToBuilder()
            .append(employee, other.employee)
            .append(total, other.total)
            .toComparison();
}

What exacly does CompareToBuilder do here? And how is it interacting with the employee and total attributes?


I did read the javadocs, but I cant make head or tail of what they are doing with the constructor and the multiple appends. Does this question indicate unclear intentions and zero research?

like image 700
Jesvin Jose Avatar asked Feb 06 '12 14:02

Jesvin Jose


2 Answers

I was trying to figure out how CompareToBuilder works myself and I came across this post, but I wasn't happy with the answer. For instance, the toComparison method should return a negative integer, a positive integer, or zero as the builder has judged the "left-hand" side as less than, greater than, or equal to the "right-hand" side.

So my question was how the order of appending attributes affect the comparison. To answer that, the only thing I could do was check the source code and I found this:

public CompareToBuilder append(int lhs, int rhs) {
    if (this.comparison != 0) {
        return this;
    }
    this.comparison = ((lhs > rhs) ? 1 : (lhs < rhs) ? -1 : 0);
    return this;
}

So, basically what is happening is that it will compare the attributes based on the order you append them. In your code example, "employee" will be evaluated first. If the left-hand side attributes evaluates as less than or greater then the right-hand side then, total is disregarded.

The attribute "total" will only be evaluated if "employee" evaluates to equal.

like image 178
chaos Avatar answered Oct 17 '22 11:10

chaos


This class is meant to assist you in building compareTo()-methods. Imagine you had more than just 2 fields in your class - manually coding your comparison-method could be quite cumbersome.

CompareToBuilder is doing that for you - each append() method is adding a new comparison, and all comparisons are &&ed.

So the code you posted runs equals() on the employee object and total.

like image 5
quaylar Avatar answered Oct 17 '22 09:10

quaylar