Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading