在我的MainActivity中,我有以下几行代码:
//data.getFirstUserInput()-1 is equal to user input.
deck.setCardNumberEmpty(data.getFirstUserInput()-1);
System.out.println("\n Cards on table");
ArrayList<Deck> deck= deck.getCards();
Collections.sort(cards);
for (Deckc: deck
System.out.print((format("%10s","\033[F[ " + c.getOneSpecificNumber())+ " ]"));}
这打印出我的随机卡号。但问题是它们没有按数字排序,
知道我能做什么吗?
卡类
public class Card {
private String cardLetter;
private String cardNumber;
private String nullValue;
public Card(String cardLetter, String cardNumber, String nullValue){
this.cardLetter = cardLetter;
this.cardNumber = cardNumber;
this.nullValue = nullValue;
}
public String getOneSpecificNumber() { return cardNumber;}
public void setCardNumber(String x){ cardNumber = x; }
private ArrayList<Deck> deck = new ArrayList();
public Deck(){
char A = 'A';
int repeats = 2, numOfCards = 8;
for ( int i = 0; i<numOfCards;i++){
for (int j = 0; j<repeats; j++){
cards.add(new Card((char) ( A + i ) + "",i+1,""));
}
}
}
答案 0 :(得分:5)
为了根据cards
cardNumber
类对Card
数组进行排序,Comparable
类必须实现compareTo()
并覆盖public class Card implements Comparable<Card> {
private String cardLetter;
private String cardNumber;
private String nullValue;
public Card(String cardLetter, String cardNumber, String nullValue){
this.cardLetter = cardLetter;
this.cardNumber = cardNumber;
this.nullValue = nullValue;
}
public int compareTo(Card c) {
if(StringUtils.isEmpty(this.cardNumber) ||
StringUtils.isEmpty(c.cardNumber)) return -1;
return Integer.parseInt(this.cardNumber) - Integer.parseInt(c.cardNumber);
}
public String getOneSpecificNumber() { return cardNumber; }
public void setCardNumber(String x) { cardNumber = x; }
}
。
以下是代码段:
StringUtils
if(null == this.cardNumber || "".equals(this.cardNumber) ||
null == c.cardNumber || "".equals(c.cardNumber)) return -1;
是Apache Commons Lang3的一部分,如果您不想将其包含在项目中,那么您可以执行以下操作:
Collections.sort(cards);
现在你必须这样做才能排序:
System.out.println("\n Cards on table");
List<Card> cards = deck.getCards();
Collections.sort(cards);
for (Card c: cards) {
System.out.print((format("%10s","\033[F[ " + c.getOneSpecificNumber())+ " ]"));
}
示例:
element_from_bytes