1

As far as I understand I can overwrite equals() in Java to handle how my class interacts with ==. Which method do I have to overwrite to be define the behavior of

MyClass obj1;
MyClass obj2;
if (obj1 > obj2){
    ...
}
Christian
  • 25,249
  • 40
  • 134
  • 225

2 Answers2

8

You can't. Java doesn't support custom operator overloading. Overriding equals doesn't affect ==. The closest you can get to < is to implement the Comparable interface, which includes a compareTo method. http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

khelwood
  • 55,782
  • 14
  • 81
  • 108
5

As far as I understand I can overwrite equals() in Java to handle how my class interacts with ==

This is wrong. The explanation is already covered here: How do I compare strings in Java?:

== tests for reference equality.

.equals() tests for value equality.


To your question:

Unlike C++ or C#, in Java you cannot overload operators.

Instead of using > and < operators you have two options.

  1. Make MyClass implement Comparable:

    public MyClass implements Comparable<MyClass> {
        @Override
        public int compareTo(MyClass other) {
            //comparison logic here...
        }
    }
    

    You will use it like this:

    MyClass obj1 = ...;
    MyClass obj2 = ...;
    if (obj1.compareTo(obj2) > 0){
        ...
    }
    
  2. Create a class that implements Comparator

    public class MyClassComparator implements Comparator<MyClass> {
        @Override
        public int compare(MyClass myClass1, MyClass myClass2) {
            //comparison logic here...
        }
    }
    

    You will use it like this:

    MyClass obj1 = ...;
    MyClass obj2 = ...;
    MyClassComparator comp = new MyClassComparator();
    if (comp.compare(obj1, obj2) > 0){
        ...
    }
    
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332