Search code examples
javagenericscomparatortype-parameter

java - Create a Comparator for a type that contains type parameters


I have a class defined as MyClass<T, S> for which I'd like to create a Comparator for MyClass where T and S extend Foo.

How can I go about doing this?

Unsuccessful attempts:

// Warning: The type parameter MyClass is hiding the type MyClass<T,S>
public class MyComparator<MyClass> implements Comparator<MyClass>

// Syntax errors and the warning from above
public class MyComparator<MyClass<T, S>> implements Comparator<MyClass<T, S>>

// Syntax errors
public class MyComparator<MyClass<T extends Foo, S extends Foo>> implements Comparator<MyClass<T extends Foo, S extends Foo>>

// Syntax errors and the warning from above
public class MyComparator<MyClass<? extends Foo, ? extends Foo>> implements Comparator<MyClass<? extends Foo, ? extends Foo>>

And various combinations of the above. What is the correct way? Thank you.


Solution

  • Your class is not generic. It always compares the same type of objects, ans this type is MyClass<? extends Foo, ? extends Foo>.

    So it should be

    public class MyComparator implements Comparator<MyClass<? extends Foo, ? extends Foo>>