-2

Could anyone tell me the logic behind this piece of code?

public int compareTo(Holder o) {
    if(o == null) return -1;
    return this.value.compareTo(o.value);
}
user1167596
  • 107
  • 1
  • 13

1 Answers1

1

It compares this against another object o.

If o is null, then this is considered smaller than o (indicated by return value -1).

Otherwise the fields value of this and o are compared and the result is returned as comparison result (-1 = smaller, 1 = greater, 0 = equal).

The rationale is to have a proper ordering of elements, e.g. to sort a list.

Stefan Winkler
  • 3,871
  • 1
  • 18
  • 35
  • 1
    In plain words, it orders `null` after everything else (with everything else in its natural order according to its `.value`). – Amadan May 12 '16 at 09:12