对于作业,我给出了以下代码,方法为空白。我一直在努力,但我仍然不明白mutator setComparer或Comparator比较器如何在这个程序中工作。我在网上研究过如何使用Comparators,但这个想法仍然不清楚。谁能给我一些指导?。
由于
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);
}
}
答案 0 :(得分:1)
当您想要在相同类型的对象之间进行不同类型的比较时,基本上您使用Comparator。例如,你有
List<Integer> list = new ArrayList<Integer>();
您希望同时进行升序排序和降序排序。你要做的是写入实现Comparator的不同类:
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的代码将决定使用哪种排序方法。
答案 1 :(得分:1)
总有2个选项
1.Your Class实现类似的接口,从而提供 compareTo()方法的实现。
2.您可以通过创建自己的比较器类来创建自己的比较器,该类实现比较器接口,从而提供 compare()方法的实现。
在第一种情况下,您只需要调用 Collections.sort(your_collection)或Arrays.sort(your_array),在第二种情况下调用 Collections.sort(your_collection,object of object) your_comparator)或Arrays.sort(you_array,集合的对象)
使用II'nd Version总是更好,因为它没有为您班级的所有馆藏定义默认排序行为。
有关详细信息,请参阅Comparator and Comparable in Java