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){
...
}
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){
...
}
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
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.
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){
...
}
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){
...
}