泛型类的比较器

时间:2014-05-01 21:28:12

标签: java generics comparator

我有一个通用类:

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类的泛型类型?

1 个答案:

答案 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);
      }
    };
  }

}