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 append
s. Does this question indicate unclear intentions and zero research?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With