Search code examples
javaobjectreturn

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


Solution

  • 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)