我不知道如何正确使用 Comparator 界面。
注意:我不想使用我在大多数代码上看到的“单行”比较器实现,这意味着:
Collections.sort(deck, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return WHATEVER;
});
同样,我不想使用它,因为我要对许多不同的 ArrayList 进行排序,每次都这样做似乎是浪费空间。我想以某种方式使其工作,将我的 compareTo 方法写在一个地方一次。
我尝试了很多不同的东西,但我是实现接口的新手,所以我可能遗漏了一些东西。
这是我的 Card 类和它的比较方法。(注意:让我为您节省一些时间,并说我对使用枚举来简化代码和比较不感兴趣,我只是想学习如何正确使用 Comparator。我知道它看起来很糟糕但我必须使用一些已经写好了代码。)
import java.util.*;
public class Card implements Comparator<Card>
{
private String number;
private int value;
private int finalValue;
private String suit;
private Player owner;
public Card(String number, String suit)
{
this.number=number;
switch (number){
case "2": this.value = 2;
break;
case "3": this.value = 3;
break;
case "4": this.value = 4;
break;
case "5": this.value = 5;
break;
case "6": this.value = 6;
break;
case "7": this.value = 7;
break;
case "8": this.value = 8;
break;
case "9": this.value = 9;
break;
case "10": this.value = 10;
break;
case "J": this.value = 11;
break;
case "Q": this.value = 12;
break;
case "K": this.value = 13;
break;
case "A": this.value = 14;
break;
}
this.suit=suit;
switch (suit){
case "Spades": this.finalValue = this.value*4;
break;
case "Hearts": this.finalValue = this.value*5;
break;
case "Clubs": this.finalValue = this.value*2;
break;
case "Diamonds": this.finalValue = this.value*3;
break;
}
}
public int compare(Card card1, Card card2)
{
Integer suitValue1;
if (card1.getSuit() == "Hearts")
suitValue1=5;
else if (card1.getSuit() == "Spades")
suitValue1=4;
else if (card1.getSuit() == "Diamonds")
suitValue1=3;
else
suitValue1=2;
Integer suitValue2;
if (card2.getSuit() == "Hearts")
suitValue2=5;
else if (card2.getSuit() == "Spades")
suitValue2=4;
else if (card2.getSuit() == "Diamonds")
suitValue2=3;
else
suitValue2=2;
Integer value1, value2;
value1 = card1.getValue();
value2 = card2.getValue();
if (suitValue1 != suitValue2)
return suitValue1.compareTo(suitValue2);
else
return value1.compareTo(value2);
}
//get methods
public int getValue()
{return this.value;}
public int getFinalValue()
{return this.finalValue;}
public String getNumber()
{return this.number;}
public String getSuit()
{return this.suit;}
public Player getOwner()
{return this.owner;}
//set methods
public void setValue(int value)
{this.value = value;}
public void setFinalValue(int finalValue)
{this.finalValue = finalValue;}
public void setNumber(String number)
{this.number = number;}
public void setSuit(String suit)
{this.suit = suit;}
public void setOwner(Player player)
{this.owner = player;}
}
这就是我的比较方法。我应该把它放在另一个班级还是什么?我试着用这个来称呼它:
Collections.sort(deck, new Comparator<Card>());
但这显然是错误的。
deck 是一个 ArrayList :private ArrayList<Card> deck = new ArrayList<Card>();
填充了各种 Card 对象。