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.
>
Look at the Comparable<E> interface that defines the "int compareTo(E)"
method. This accomplishes the same thing as the six comparison operators
(although you can argue that C++'s operator==() is more like Java's
equals() method). How it works is you compare the result of that to
zero. Here are some examples:
// C++
std::string str1("a");
std::string str2("b");
bool comparison = (str1 < str2);
// Java
String str1 = "a";
String str2 = "b";
boolean comparison = (str1.compareTo(str2) < 0);
Notice how the comparison operator is the same, and the strings appear
in the same order. Under the hood Java is performing an extra operation,
comparing the two strings and then comparing the result to zero. C++ is
performing one comparison, but hiding it behind a "primitive" operator
that really calls a function.
Throughout much of the Collections framework and elsewhere you will see
discussion about "ordering consistent with equals." It is possible that
object1.compareTo(object2) == 0, yet object1.equals(object2) is false.
BigDecimal is a perfect example: two decimals may be equivalent in value
yet not equal (2.0 and 2.00, for example). This is an extra layer of
stuff on top of what C++ has by default, and something you should keep
an eye on. It is neither better nor worse, just different, and something
that can cause subtle bugs if you are not used to it.
One last note: you are better off with a List than a Vector. C++ uses
std::vector as its basic dynamic array. Java uses it for the same
purpose, but it adds synchronization, which is slow. Prefer to use
ArrayList, which is not thread safe. If need be you can wrap it in a
synchronized facade (Collections.synchronizedList() I believe), or use
one of the concurrency framework lists that are copy-on-write and
implement the same List interface.
Another last note: iterators behave slightly differently in Java and
C++. While they solve similar problems, they do so differently. In
particular, there is no algorithms package that accepts iterators in
Java like there is in C++. You can do the same things, you just get
there a different way.
--
John Gaughan