-1

Consider having this class in Java:

public class Foo implements Comparable<Foo> {
    private int someValue;

    @Override
    public int compareTo(Foo o) {
        if (this.someValue < o.someValue) {
            return -1;
        } else if (this.someValue == o.someValue) {
            return 0;
        } else {
            return 1;
        }
    }
}

I tried to do this:

Foo foo1 = new Foo(someValue);
Foo foo2 = new Foo(someAnotherValue);
if (foo1 < foo2) {
   // do something
}

But the IDE is giving me an error which is: "Bad operand types for binary operation '<' first type: Foo, second type: Foo"

May you please tell me what is wrong?

Thanks in advance for your help,

Ambitions
  • 2,369
  • 3
  • 13
  • 24

1 Answers1

4

Implementing the Comparable interface is a good first step to being able to compare your objects properly. However, that doesn't allow you to use the < and > comparison operators as if the operators were overloaded. You just need to call your compareTo method.

if (foo1.compareTo(foo2) < 0) {
rgettman
  • 176,041
  • 30
  • 275
  • 357