user3506
user3506

Reputation: 119

Java Strings object in ArrayList

In my MainActivity I have this lines of code:

    //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())+ " ]"));}

This prints out my random card numbers. But the problem is they are not numerically sorted,

Any idea what I can do?

Card Class

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,""));
        }
    }
}

Upvotes: 2

Views: 104

Answers (1)

ninja.coder
ninja.coder

Reputation: 9648

In order to sort the cards Array as per the cardNumber your Card class has to implement the Comparable and override compareTo().

Here is the code snippet:

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 is part of Apache Commons Lang3, if you do not want to include it in your project then you can do something like this:

if(null == this.cardNumber || "".equals(this.cardNumber) ||
       null == c.cardNumber || "".equals(c.cardNumber)) return -1;

Now you just have to do this in order to sort:

Collections.sort(cards);

Example:

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())+ " ]"));
}

Upvotes: 5

Related Questions