How to convert a raw Comparator type to a generic type.
I have a situation requiring a generic Comparator type, for now this has been implemented using a raw Comparator type, but I would like to rewrite this to a genuine generic type, unfortunately without success yet. Basically what I would like to achieve is something like:
publicclass Test
{
publicint myCompare( Comparator<?extends Object> cmp, Object e1, Object e2 )
{
return cmp.compare(e1,e2);
}
}
I have tried several versions of the unbounded wildcard, but they all seem to result in some kind of compiler error, the above attempt results in something like:
"The method compare(capture-of ? extends Object, ... is not applicable for the arguments (Object, Object )."
Question is how to write this down properly?
Regards,
Wieant
[1131 byte] By [
Wieanta] at [2007-10-3 1:04:38]

Hi,
Could be that I don't understand the question, but what about this?
public class Test {
public <T> int myCompare(Comparator<T> cmp, T e1, T e2 ) {
return cmp.compare(e1,e2);
}
}
Kaj
kajbja at 2007-7-14 18:01:01 >

Nice solution! Unfortunately my code example might have been a bit too simplistic. Actually I'm writing a table wrapper that allows you to add columns including a comparator that can be used for sorting elements in the column. So a slightly altered example would look like:
public class GenericCompare
{
// Note, the forum's formatter seems to think an extra > is needed right after Comparator?
Vector<Comparator><?>> cmps;
public int myCompare( int column, Object e1, Object e2 )
{
return cmps.get(i).compare(e1,e2);
}
}
In which myCompare can be called with any e1, e2 Object type. Joachim seems to be right there is no type-safe way to write this down, the above example triggers an error, and using a raw Comparator cast to solve that triggers a type safety warning.
Regards,
Wieant