Question

I have a generic class Card . Rank is interface

class Card<T extends Enum<T> & Rank>

I am trying to create two static comparators of Card.

public final static Comparator<Card<?>> comparatorByAttribute1 = new Comparator<Card<?>>() { 
     @Override
     public int compare(Card<?> o1, Card<?> o2) 
     { 
       ... 
     } 
}; 

How can I define that the type of o1 should be the same with o2 ?

Was it helpful?

Solution

Why not just use the actual type in the type declaration?

public final static Comparator<Card<ActualType>> comparatorByAttribute1 = 
    new Comparator<Card<ActualType>>() {

        @Override
        public int compare(Card<ActualType> o1, Card<ActualType> o2) {
            return 0;
        }
    };

With...

public enum ActualType implements Rank {...}

Alternatively, if you want to keep the generic type <T>, you will need to resort to using a generic static method, because there is no way of having generic attributes in Java:

public final static <T extends Enum<T> & Rank> Comparator<Card<T>> 
    comparatorByAttribute1() {
    return new Comparator<Card<T>>() {

        @Override
        public int compare(Card<T> o1, Card<T> o2) {
            return 0;
        }
    };
}

Or, you resort to unsafe casting:

@SuppressWarnings({ "rawtypes", "unchecked" })
public final static <T extends Enum<T> & Rank> Comparator<Card<T>> 
    comparatorByAttribute1() {
    // Your attribute
    return (Comparator) comparatorByAttribute1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top