Dave's Brain

Browse - Programming Tips - How can I override the = = operators in Java as I can in C++ ?

Date: 2013oct22
Language: Java

Q.  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 }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.