对于家庭作业,我得到了以下代码,其中方法为空白。我一直在研究它,但我仍然不明白 mutator setComparer 或 Comparator comparer 在这个程序中是如何工作的。我在网上研究了如何使用比较器,但这个想法仍然不清楚。谁能给我一些指导?
- 我是否必须初始化 Comparator 比较器?如果是这样,我该怎么做?
- private int compare(PlayingCard one, PlayingCard two) 上面的评论是什么意思?(this.comparer=null)
谢谢
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);
}
}