Date: 2013oct22
Language: Java
Q. Java: How can I override the > < <= >= operators in Java as I can in C++ ?
A. You can't but here is the next best thing.
Override the equals() method and a compare() method like this:
class MyClass implements Comparator<MyClass> {
// Other code for your class here
@Override
public boolean equals(Object obj) {
// Your code here
}
@Override
public int compare(MyClass a, MyClass b) {
// Your code here
// Return 1 if a > b
// Return -1 if b > a
// Return 0 if they are equal
}
}
Now users of you class can do:
if (one.compare(one, two) >= 0) {
// One is greater than or equal to two
}