问题
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