# 如何实现比较使用的compareTo（）

##### 问题描述投票：1回答：2

``````public class Card implements Comparable<Card> {
public enum rank {TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE};
private rank Rank;
public enum suit {CLUBS, DIAMONDS, HEARTS, SPADES};
private suit Suit;
}
``````

，我需要执行两个任务。首先 - 制作卡片类可比，这样的compareTo可以用来卡的升序排列。我在这里所做的是：

``````@Override
public int compareTo(Card other) {
if(this.Rank != other.Rank) {
if(this.Rank.ordinal() > other.Rank.ordinal()) {
return 1;
}
else if(this.Rank.ordinal() < other.Rank.ordinal()) {
return -1;
}
else {
return 0;
}
}
else {
if(this.Suit.ordinal() > other.Suit.ordinal()) {
return 1;
}
else if(this.Suit.ordinal() < other.Suit.ordinal()) {
return -1;
}
else {
return 0;
}
}
}
``````

``````public static class CompareDescending implements Comparator<Card> {
@Override
public int compare(Card card, Card other) {
if(card.Rank != other.Rank) {
if(card.Rank.ordinal() < other.Rank.ordinal()) {
return 1;
}
else if(card.Rank.ordinal() > other.Rank.ordinal()) {
return -1;
}
else {
return 0;
}
}
else {
if(card.Suit.ordinal() < other.Suit.ordinal()) {
return 1;
}
else if(card.Suit.ordinal() > other.Suit.ordinal()) {
return -1;
}
else {
return 0;
}
}
}
}
``````

java
##### 2个回答
5

`compareTo`是过于复杂。

`enum`实现`compareTo`为你，为按序号在声明的顺序排序枚举值，即。

``````@Override
public int compareTo(Card other) {
int cmp = this.Rank.compareTo(other.Rank);
if (cmp == 0)
cmp = this.Suit.compareTo(other.Suit);
return cmp;
}
``````

``````public static class CompareDescending implements Comparator<Card> {
@Override
public int compare(Card card, Card other) {
return other.compareTo(card); // descending
}
}
``````

0

``````class Card implements Comparable<Card> {

public static final Comparator<Card> SORT_ASC = Comparator.<Card, Rank>comparing(card -> card.rank).thenComparing(card -> card.suit);
public static final Comparator<Card> SORT_DESC = SORT_ASC.reversed();

private Rank rank;
private Suit suit;

@Override
public int compareTo(Card card) {
return SORT_ASC.compare(this, card);
}

public enum Rank {}
public enum Suit {}
}
``````

``````List<Card> cards = Collections.emptyList();
List<Card> asc = cards.stream().sorted(Card.SORT_ASC).collect(Collectors.toList());
List<Card> desc = cards.stream().sorted(Card.SORT_DESC).collect(Collectors.toList());
``````