2

我想使用类的方法对我的Deque<Card>集合的内容进行排序。CardgetRealValue()

public class Card implements Comparable<Card> {
  private final int value;
  private final CardType cardType;

  public Card(int value, CardType cardType) {
    this.value = value;
    this.cardType = cardType;
  }

  public int getRealValue() {
    int realValue = this.value == 1 ? 52 : 0;
    return realValue + this.value * 4 + this.cardType.ordinal();
  }

  public int compareTo(Card o) {
    return this.getRealValue() - o.getRealValue();
  }
}

这是我的 CardType 枚举

public enum CardType {
    CLUB("♣"),
    SPADE("♠"), 
    HEART("♥"), 
    DIAMOND("♦"); 

    public final String icon;

    private CardType(String icon) {
        this.icon = icon;
    }
}

我想根据我的 Deque 排序realValue()

4

1 回答 1

3

好吧,您总是可以清除它并以正确的顺序重新插入元素:

Card[] a = deque.toArray(new Card[0]);
Arrays.sort(a);
deque.clear();
for (Card card : a) {
    deque.add(card);
}

请记住这一点的表现。如果排序是您的结构的要求,请考虑使用PriorityQueue.

于 2019-05-31T12:43:54.193 回答