Sort java.util.Deque

不问归期 提交于 2021-02-16 21:04:57

问题


I want to sort the contents of my Deque<Card> collection using the Card class' getRealValue() method.

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();
  }
}

Here is my CardType enum

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

    public final String icon;

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

and I want to sort my Deque based on the realValue()


回答1:


Well you can always clear it and re-insert the elements in the right order:

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

Bear in mind the performance of this. If sorting is a requirement of your structure, consider using a PriorityQueue.



来源:https://stackoverflow.com/questions/56395129/sort-java-util-deque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!