我担心我对这个问题的措词有误,所以这里有一个例子来说明:
我有一个界面:
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
方法采用类型为ICard
的参数,尽管我想比较从IDeck继承的牌组。 最佳答案
您可以使您的ICard
接口具有绑定的泛型,因此任何泛型类型参数本身都必须为ICard
。
public interface ICard<T extends ICard<T>> extends Comparable<T>{
然后,您可以在
PlayingCard
类的ICard
界面中指定PlayingCard
:public class PlayingCard implements ICard<PlayingCard> {