我有一个通用类:
class Card<T extends Enum<T> & Rank> implements Comparable<Card<T>>
Rank
是java接口。
我正在尝试在Comparator
类中创建一个Card
实例。
public final static Comparator<Card> comparator = new Comparator<Card>() { ... }
上一行有警告。
卡片是原始类型。应该参考通用类型卡 参数
如何声明Card
类的泛型类型?
答案 0 :(得分:0)
public class Card<T extends Enum<T> & Rank> {
private final T rank;
private final Suit suit;
public Card(T rank, Suit suit)
{
this.rank = rank;
this.suit = suit;
}
public final static <T extends Enum<T> & Rank> Comparator<Card<T>> byRank()
{
return new Comparator<Card<T>>() {
@Override
public int compare(Card<T> o1, Card<T> o2)
{
int r = compareRank(o1, o2);
return r != 0 ? r : compareSuit(o1,o2);
}
};
}
public final static <T extends Enum<T> & Rank> Comparator<Card<T>> bySuit()
{
return new Comparator<Card<T>>() {
@Override
public int compare(Card<T> o1, Card<T> o2)
{
int r = compareSuit(o1,o2);
return r != 0 ? r : compareRank(o1, o2);
}
};
}
}