-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,

2
  • 3
    You can't. Those operators can only be used with numeric types. Foo is not a numeric type. Commented Apr 12, 2016 at 21:54
  • Java (unlike some other languages), does not support operator overloading. Commented Apr 12, 2016 at 21:57

1 Answer 1

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) {
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.