How to compare two different generic instantiations of a class in Java?

MRE because well, assignment… sigh

This is the problem I’m stuck on:
Consider the following class:

class MyClass<T extends Comparable<T>> implements Comparable<MyClass<T>> {

... override the compareTo
}

This allows me to compare MyClass<Integer> with another MyClass<Integer> or even MyClass<MyClass<Integer>> with another MyClass<MyClass<Integer>>.
However, the assignment requires me to be able to compare MyClass<MyClass<Integer>> with MyClass<MyClass<String>> as the comparison just uses a counter and returns whichever class has the bigger counter as the greater of the two.
How would I go about achieving this? My guess is that the Comparator comes into play as is apparent here. However, I’m not able to quite put my finger on it. Is it as simple as just using the compare(Object,Object) from the Comparator or is it something else?

>Solution :

You can use ? knowns as wildcard instead of specifying the type explicitly:

class MyClass<T extends Comparable<T>> implements Comparable<MyClass<?>> {
    private int counter; // or any other variable
    
    @Override
    public int compareTo(MyClass<?> o) {
        return counter - o.counter;
    }
}

And then use it like:

MyClass<String> string = new MyClass<>();
MyClass<Integer> integer = new MyClass<>();

int result = string.compareTo(integer);

Leave a Reply