То, что у вас здесь есть, называется copy-initialization .
A a = "qweqeasd";
Если
blockquote>T
является типом класса и cv-безусловной версией типа other является T или класс, производный от T, рассматриваются неявные конструкторы изT
и наилучшее совпадение выбирается по разрешению перегрузки. Затем вызывается конструктор для инициализации объекта.Здесь лучшее совпадение - конструктор
A(const char * ch)
, и поэтому вывод начинается сcontruct
.
Один из вариантов - реализовать интерфейс Comparable, а затем переопределить CompareTo. Once you've done that, sorting the list is easy with Collections.sort(myCollection);
You may be better of avoiding implementing Comparable and create a Comparator object, and there's a version of Collections.sort that takes the comparator.
Your comparison function can can then simply check the rank of the cards, and return the result while ignoring the suit.
You may want to read the Java tutorial on all this ordering business.
Update: Bjorn points out correctly that Comparable should be used when the class has a natural sorting order. My personal view is that for cards there isn't really a "natural order" since different games differ in their interpretation of the Ace, so it might be better to avoid assigning "semantics" by offering Comparable as part of the class.
Код был бы намного чище, если бы вы использовали enum для представления ранга и набора вместо char.
Фактически, http://jcp.org/aboutJava/communityprocess/ jsr / tiger / enum.html имеет образец карты, иллюстрирующий использование Enum
Соответствующий бит кода скопирован ниже
public class Card implements Comparable, java.io.Serializable {
public enum Rank { deuce, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace }
public enum Suit { clubs, diamonds, hearts, spades }
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
if (rank == null || suit == null)
throw new NullPointerException(rank + ", " + suit);
this.rank = rank;
this.suit = suit;
}
public Rank rank() { return rank; }
public Suit suit() { return suit; }
public String toString() { return rank + " of " + suit; }
public int compareTo(Object o) {
Card c = (Card)o;
int rankCompare = rank.compareTo(c.rank);
return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit);
}
private static List<Card> sortedDeck = new ArrayList<Card>(52);
static {
for (Iterator<Rank> i = Rank.VALUES.iterator(); i.hasNext(); ) {
Rank rank = i.next();
for (Iterator<Suit> j = Suit.VALUES.iterator(); j.hasNext(); )
sortedDeck.add(new Card(rank, j.next()));
}
}
// Returns a shuffled deck
public static List<Card> newDeck() {
List<Card> result = new ArrayList<Card>(sortedDeck);
Collections.shuffle(result);
return result;
}
}
The Missing CompareTo code:
ArrayList<Card> aCardList = new ArrayList<Card>();
Collections.sort(aCardList, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
if (o1.getRank() > o2.getRank())
return -1;
else if (o1.getRank() < o2.getRank())
return 1;
else
return 0;
}
});
You can implement the Comparable interface such that the elements are compared by rank. Then Collections.sort will automatically do what you expect it to do.
Несколько более коротких методов
public String toString() {
return "" + rank + suit;
}
public boolean isValidCard(){
return "HSDC".indexOf(suit) != -1 &&
"A23456789TJQK".indexOf(rand) != -1;
}
You could use thejava.util.Collections class to sort it. Particularly, two methods may come handy:
static <T extends Comparable<? super T>>
void sort(List<T> list)
Sorts the specified list into ascending order, according to the natural ordering of its elements.
static <T> void sort(List<T> list, Comparator<? super T> c)
Sorts the specified list according to the order induced by the specified comparator.
For the first method, you should make your Card class implement the Comparable interface.. For the second one, you should provide a custom comparator.
This is done in order for the collections framework to know how to compare your Card objects.
So, for example (first method), you would have this code:
In your card class
public Class Card implements Comparable{
//member and method definitions.
public int compareTo(Object o){
//null checks && stuff missing.
/*compares two cards based on rank.*/
}
List<Card> cards = getAllCards();//returns an unsorted list implementation of Card objects.
java.util.Collections.sort(cards);