我担心我用错了这个问题的措辞,所以这里有一个例子来说明:
我有一个界面:
public interface ICard extends Comparable<T>{
public abstract String toString();
public abstract int compareTo(T o) throws WrongCardTypeException;
}
我想要的是实现 ICard 的类自动实现Comparable<T>
,以便您只能比较实现 ICard 的任何类
相反,我需要为可比较的扩展指定泛型并使用下面的那种instancof
检查
public interface ICard extends Comparable<ICard>{
public abstract String toString();
public abstract int compareTo(ICard o) throws WrongCardTypeException;
}
public class PlayingCard implements ICard{
public enum Rank { TWO, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
private Rank rank;
private Suit suit;
public PlayingCard(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank getRank() { return rank; }
public Suit getSuit() { return suit; }
@Override
public String toString() { return rank + " of " + suit; }
@Override
public int compareTo(ICard o) throws WrongCardTypeException {
if (o instanceof PlayingCard){
PlayingCard c = (PlayingCard)o;
int rankCompare = rank.compareTo(c.rank);
return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit);
}
throw new WrongCardTypeException("Tried to compare "+o.getClass().getCanonicalName()+" to "+ this.getClass().getCanonicalName());
}
我想知道是否有一种更简洁的方法可以让我取消instanceof
支票?通配符?我不确定这里。还是instanceof
支票没问题?我听说它有“代码气味”,例如是不好的做法。
我的 IDeck 界面也有类似的 (?) 问题:
public interface IDeck<T extends ICard> extends Comparable<T>, Collection<T>{
public ArrayList<T> getDeck();
public void setDeck(Set<T> newDeck);
}
在实现这一点的类中,我的compareTo
方法采用 type 的参数ICard
,但我想比较从 IDeck 继承的牌组。