Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object: value for comparison in if statement, operator overloading

Is it possible to define the value used for if statement comparison for custom objects?

I have:

public class element implements Comparable {

public int value;
public int[] sequence;
public int length;

public element(){}   

public element(int val){
    this.value = val;
}

@Override
public int compareTo(Object o) {
    return
}

}

I would like to use and if statement as follows:

if (element1 > element2) ..

Instead of a traditional:

if (element1.value > element2.value) ..

I have been unable to acomplish this with comparators, toString() etc

like image 692
RyanS Avatar asked Sep 29 '26 04:09

RyanS


1 Answers

You cannot use object references with the > operator, per JLS 15.20.1; Java does not support operator overloading. But you are on the right track with using a Comparator.

if (comparator.compare(element1, element2) > 0)  // if (element1 > element2)

It is also possible if your class is Comparable<Element>, i.e. comparable to other elements.

if (element1.compareTo(element2) > 0)  // if (element1 > element2)
like image 135
rgettman Avatar answered Sep 30 '26 17:09

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!