排序 java.util.Deque

Ran*_*las 2 java collections arraydeque

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

\n\n
public class Card implements Comparable<Card> {\n  private final int value;\n  private final CardType cardType;\n\n  public Card(int value, CardType cardType) {\n    this.value = value;\n    this.cardType = cardType;\n  }\n\n  public int getRealValue() {\n    int realValue = this.value == 1 ? 52 : 0;\n    return realValue + this.value * 4 + this.cardType.ordinal();\n  }\n\n  public int compareTo(Card o) {\n    return this.getRealValue() - o.getRealValue();\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我的 CardType 枚举

\n\n
public enum CardType {\n    CLUB("\xe2\x99\xa3"),\n    SPADE("\xe2\x99\xa0"), \n    HEART("\xe2\x99\xa5"), \n    DIAMOND("\xe2\x99\xa6"); \n\n    public final String icon;\n\n    private CardType(String icon) {\n        this.icon = icon;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想根据以下内容对双端队列进行排序realValue()

\n

man*_*uti 5

那么您始终可以清除它并以正确的顺序重新插入元素:

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

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

  • 您可以使用 [`Collections.addAll`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#addAll-java.util .Collection-T...-)(至少在 OpenJDK 中,以相同的方式实现:https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes /java/util/Collections.java#l5429,https://hg.openjdk.java.net/jdk/jdk15/file/cd766db99c40/src/java.base/share/classes/java/util/Collections.java#l5562 )。 (3认同)