This is the complaint that I had when I moved from C++ to Java. How
could a language so advanced not have overloaded operators?
Well, that's a choice (a poor one, IMHO) that the designers of Java
made, and we poor schmucks have to live with it.
There's a couple of ways you can get around this:
1) Use the hashCode () method on both objects. Every Java object has this.
TypeA objA = new TypeA (...);
TypeA objB = new TypeA (...);
if (objA.hashCode () < objB.hashCode ()) {
...
2) Use the equals () method. Every Java object has this.
TypeA objA = new TypeA (...);
TypeA objB = new TypeA (...);
if (objA.equals (objB)) {
...
Of course, this may mean that TypeA must override the default behavior
of comparing the references for equality.
3) Implement the compareTo () method. This is available by implementing
the Comparable interface. This method is used extensively by objects
that implement Comparator. TreeSet and TreeMap use Comparator objects
under the hood to sort their objects. So:
TypeA objA = new TypeA (...);
TypeA objB = new TypeA (...);
TreeSet<TypeA> ts = new TreeSet<TypeA> ();
ts.add (objA);
ts.add (objB);
will put objA and objB in order, according to the compareTo () method.
Hope this helped.
-Java Guy
samir wrote:
>
> Recently, I moved to Java from C++ as I love the language and its features
> very much. However, there is a little problem I am facing while writing
> comparison functions. In C++, it was easy to overload the < operator for
> user defined class. But how to achieve the same elegantly in Java while
> using custom classes? I will need to use these because of sorting
> vectors in
> out-of-the-norm fashion.
> Thank you in advance...
>
> [Non-text portions of this message have been removed]
>
>