Re: Comparable loses its interface powers.
Roedy Green wrote:
If Comparable were just an ordinary interface you could say things
....
But generics butt in and it seems to be impossible to keep around
arrays of Comparables for sorting columns.
The problem here is that the Comparable interface is designed for the
class itself to compare to other objects. If you were the one
implementing this method, how many classes would you want to compare it
to?
Using your example of comparing Strings and Double, let's look at String
method:
public int compareTo( Object o ) {
if( o instanceof String )
... normal string compare...
else if( o instanceof Double )
... compare String to Double...
else if( o instanceof Integer )
... how many of these do you want?
It just goes on and on. Frankly, I think your question lacks any sort
of critical thought. It's pretty obvious what would happen if one
actually tried to implement your idea. Not good things.
And of course, this code would have to be duplicated inside Double, and
Integer, and every other class that you wanted to compare to. That the
real issue for me. It's just a stinky idea.
One way, which I find ugly is to sort Objects instead of Comparables
Ugly is as ugly does, I suppose. Maybe don't use Object? A little
effort wouldn't hurt here.
Let's see, off the top of my head. We don't want to compare Objects, so
we do want to make our own type.
public interface MyColumnType {}
It's just a marker interface for now. So we want to compare Strings,
but we can't extend String. We'll have to use composition.
Fortuneately, there's a string-like interface, CharacterSequence that
will help
public class MyStringType implements CharacterSequence, MyColumnType
private final String value;
public MyStringType( String v ) { value = v; }
....
}
We can't extend Double either, but there is a common Number class we can
use:
public class MyNumericType extends Number implements MyColumnType
private final Number value;
public MyNumericType( Number n ) { value = n; }
...
}
Now we can use a Comparator to implement the actual comparison
public class MyColumnComparator implements Comparator<MyColumnType>
{
public void compare(MyColumnTye o1, MyColumnTye o2 ) {
.. implement here..
}
}
Now at least it looks like someone made some sort of effort. I don't
have an algorithm for comparing Strings and Numbers for you, but then I
don't know how you want to compare them. It's a critical detail you
conveniently left out. I don't think there is a standard way of
comparing them, do you? So I'll just leave the rest of it to you then.