2

Is there a plug in that supports compare operations on a custom object?

I would like to use this:

class MyTemperatureObject implements Comparable<MyTemperatureObject> {
    ...
    @Override
    public int compareTo(MyTemperatureObject object) {
       return getValue().compareTo(object.getValue());
    }
}

MyTemperatureObject a;
MyTemperatureObject b;

if (a < b){
    ...
}

This gives the compile error:

Operator '<' cannot be applied to MyTemperatureObject

But I think that the compiler can use the Comparable interface to evaluate this. Or is there maybe a reason that this is not possible or not wisely to do this.

I know that I can use the compareTo function

a.compareTo(b) < 0

But I think this is better readable/understandable

 a < b
bmooij
  • 142
  • 2
  • 9

4 Answers4

5

In Java, the < operator can only be used on numeric types. The compiler will not automagically apply the compareTo method for object comparisons.

Rewrite your condition as follows:

if (a.compareTo(b) < 0){ /* ... */ }

The semantics of the compareTo method are clearly documented in the JavaDoc, but in essence it boils down to this:

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 2
    I think you should explain him the return value of the `compareTo` method as well. – Dragos Rizescu Apr 20 '15 at 07:14
  • I know this function I have implemented this function. But what I want is to not use this function. a < b is more understandable than a.compareTo(b) < 0 – bmooij Apr 20 '15 at 07:16
  • But what are the downsides for to not support this? – bmooij Apr 20 '15 at 07:18
  • 1
    I don't see any immediate downsides. Dealing with `null` cases would probably be a little bit tricky, as well as dealing with incompatible types. All issues that could probably be solved more or less elegantly, but I can't speculate about the original language designers' motivations. – Robby Cornelissen Apr 20 '15 at 07:21
2

if you want to do like on C++ operator overloading : Wikipedia - C++ Operator Overloading, then it doesn't exist on java.

Vyncent
  • 1,185
  • 7
  • 17
0

You can refer documentation of compareTo method.

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

You can use compareTo method.

if (a.compareTo(b) < 0){
    // Your code
}

Operator '<' cannot be applied to MyTemperatureObject

Answer : Operator overloading is not supported in Java, as it is supported in C++. So you can use < / > operator for numeric comparison only.

Naman Gala
  • 4,670
  • 1
  • 21
  • 55
0

You must use specific class that invoke compareTo method, Take a look as this tutorial, I hope help you http://www.tutorialspoint.com/java/java_using_comparator.htm

AKZ
  • 856
  • 2
  • 12
  • 30