testing weather one object is greater than another object
Hey everyone, I have to write a compare method that takes two parameters. I would like to know if I can compare one object with another by comparing if it is greater or less than the other one. I know its possible to test if two objects are equal so I assume it could be done!
Re: testing weather one object is greater than another object
In general references to objects can be compared with == or !=, that is they do or do not refer to the same thing. And that's all: there is no well defined concept of reference value ordering. (as there might be if references were pointers to memory locations as they are in some other languages.)
That's references, but what about the things they reference? These things (instances of String, Double, Point etc) have an equals() method that will test whether the things should be considered equal. And they sometimes have a method that allows one thing to be compared to another. Classes that do have a method allowing their instances to be compared implement the Comparable interface. Some classes (like String and Double) do implement Comparable, and some (like Point) do not.
It is also possible to write a class which implements the Comparator interface. Basically such a class would implement a method like the one you describe. You would write such a method yourself: ie there is no built in support for such comparisons (for the reason mentioned). Writing classes with such a method (ie that implement comparator) is discussed in Oracle's Tutorial in the Object ordering page of the Collections trail.