对于家庭作业,我得到了下面的代码,其中的方法为空白。我一直在做它,但我仍然不明白突变体setComparer或比较器是如何在这个程序中工作的。我已经在网上研究过如何使用比较器,但是这个想法还不清楚。有人能给我一些指导吗?
谢谢
import java.util.*;
//Class to represent a "generic" hand of playing-cards
public class PlayingCardHand {
//Instance Variables
private int cardsInCompleteHand; //Maximum # cards in this hand
private ArrayList<PlayingCard> hand; //A hand of Playing-Cards
private Comparator comparer; //Client-provided comparison of PlayingCards
//Constructor
//Appropriate when PlayingCard compareTo() is to be used to compare PlayingCards
public PlayingCardHand(int handSize) {
cardsInCompleteHand = handSize;
hand = new ArrayList<PlayingCard>();
}
//Helper: Compare 2 PlayingCards
// if this.comparer is null, comparison uses compareTo()
// otherwise the Comparator is applied
private int compare(PlayingCard one, PlayingCard two) {
return 0;
}
//Accessor: return # of cards currently in this hand
public int getNumberOfCards() {
return cardsInCompleteHand;
}
public boolean isComplete() {
if (hand.size() == cardsInCompleteHand) {
return true;
}
return false;
}
//Accessor: return COPIES of the cards in this hand
public PlayingCard[] getCards() {
PlayingCard[] temp = new PlayingCard[hand.size()];
for (int i = 0; i < hand.size(); i++)//ch
{
temp[i] = hand.get(i);
}
return temp;
}
//Mutator: allows a client to provide a comparison method for PlayingCards
public void setComparer(Comparator comparer) {
}
//Mutator: Append a new card to this hand
public void appendCard(PlayingCard card) {
int counter = 0;
PlayingCard.Suit su = card.getSuit();
PlayingCard.Rank ra = card.getRank();
PlayingCard temp3 = new PlayingCard(su, ra);
//10 20 goes here 30 40 if insert 25
for (int i = 0; i < hand.size(); i++) {
PlayingCard temp4 = hand.get(i);
PlayingCard.Suit sui = temp4.getSuit();
PlayingCard.Rank ran = temp4.getRank();
if (su.ordinal() <= sui.ordinal() && ra.ordinal() <= ran.ordinal()) {
hand.add(i, temp3);
counter++;
}
}
while (counter == 0) {
hand.add(temp3);
}
}发布于 2013-05-19 16:44:40
基本上,当您想要在同一类型的对象之间进行不同类型的比较时,可以使用比较器。例如,你有
List<Integer> list = new ArrayList<Integer>();您希望同时进行升序排序和降序排序。您要做的是写到实现比较器的不同类:
public class Ascending implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
}
}
public class Descending implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return (o1<o2 ? -1 : (o1==o2 ? 0 : 1));
}
}然后可以对数组进行排序:
Collections.sort(list, new Descending());你的问题的答案是:
1-这取决于您如何使用类PlayingCardHand。据我所见你需要初始化它。
2-注释意味着使用PlayingCardHand的代码将决定使用何种排序方法。
发布于 2013-05-19 17:02:05
总有两个选项可用
1.类实现了类似的接口,从而提供了compareTo()方法的实现。
2.通过创建自己的比较器类来创建自己的比较器,该类实现了比较器接口,从而提供了compare()方法的实现。
在第一种情况下,只需调用Collections.sort(your_collection)或Arrays.sort(your_array),在第二种情况下,调用作为Collections.sort(your_collection,对象的your_comparator)或Arrays.sort(you_array,集合的对象)。
使用II‘’nd版本总是更好,因为它没有为类的所有集合定义默认的排序行为。
有关更多详细信息,请参阅比较器和Java中的可比
https://stackoverflow.com/questions/16636523
复制相似问题