Rhino wrote:
> I need a sanity check on a design I am considering.
>
> I am trying to design a simple class called Range, which subclasses Object.
> I want Range to store a two-element array of Objects that are both of the
> exact same class. However, I only want to store Objects if it is possible to
> determine which of the two is the lower value. Integers have intrinsic order
> so two Integers can obviously can be compared to see which is lower, however
> two JPanels do not have intrinsic order (aside from creation sequence which
> I consider irrelevant for my purposes) so they have no intrinsic order.
> Therefore, I have no problem in creating a Range of Integers but don't want
> to create a Range of JPanels.
>
> It seems to me that my best approach is to see if the Objects that are
> passed to my Range constructor implement the Comparable interface. If they
> do, I can compare the two Objects in the constructor and determine which is
> the lower value.
>
> I can use the getInterfaces() method in Class to determine the interfaces
> implemented by the incoming Objects and then use the compareTo() method
> defined for that class to find out which is lower, then store it as a class
> variable called 'lowValue'; the other Object gets stored in 'highValue'.
> Then I can write a between() method to determine if a third value is within
> the Range defined by the two Objects in the Range.
>
> Is this design basically sound?
The design is sound, but you're working far too hard.
Just define the Range constructor to take two Comparable
objects:
public Range(Comparable x, Comparable y)
Now, this isn't *quite* enough, because two classes that
implement Comparable might not be comparable to each other:
if `x' is a String and `y' is an Integer, both implement
Comparable but the attempt to use either's compareTo()
method on the other will fail. However, since you're
planning to use compareTo() anyhow to discover how `x'
and `y' map to `lowValue' and `highValue', any such problem
will be detected immediately: the compareTo() method will
throw an exception and the constructor will exit.
(Advanced and optional topic: See also Comparator for
a way to compare non-Comparable objects.)
> Followup question: If this design is sound, how do I compare the actual
> values of the Objects? In my constructor, I know that they belong to the
> same class and that the class implements Comparable but how do I actually
> see which is lower? I have to cast them from Object to their actual class
> and then do compareTo() right?
No cast is needed; just use compareTo(). That's what
polymorphism is all about.
Forgive me for saying so, but several of your questions
have a strong "beginner flavor" about them, which suggests
that they probably belong in comp.lang.java.help rather than
here. It also suggests that you need to drag out your Java
textbook again and re-read it; something didn't "take" the
first time around.
--