5

Hi I have Card class... In another class I create an arrayList of Card objects. How would I go about sorting the arrayList based on the value of the card? The ace is the lowest card value and the king is the highest.

A,2,3,4,5,6,7,8,9,T,J,Q,K

public class Card {
 char rank, suit;
 public Card(char rank, char suit){
 this.rank = rank;
 this.suit = suit;
 }
 public void setCard(char rank, char suit){
 this.rank = rank;
 this.suit = suit;
 }
 public char getRank(){
 return rank;
 }
 public char getSuit(){
 return suit;
 }
 public void setRank(char rank){
 this.rank = rank;
 }
 public void setSuit(char suit){
 this.suit = suit;
 }
 public String toString(){
 String str = "";
 str += this.getRank();
 str += this.getSuit();
 return str;
 }
 public boolean equals(Object obj){
 Card card = (Card) obj;
 if(this.rank == card.getRank() && this.suit == card.getSuit()){
 return true;
 }
 return false;
 }
 public boolean isValidCard(Card card){
 char s = card.getSuit();
 char r = card.getRank();
 if(s=='H' || s=='S' || s=='D' || s=='C'){
 if(r=='A' || r=='2' || r=='3' || r=='4' || r=='5' || r=='6' || r=='7' || 
 r=='8' || r=='9' || r=='T' || r=='J' || r=='Q' || r=='K'){
 return true;
 } 
 }
 return false;
 }
 public boolean allowedInHigherPiles(Card card, Game game, int pile){
 if(pile>=5 && game.getPile(pile).cards.size()==0){
 if(card.getRank()!='K')
 return false;
 }
 return true;
 }
}
IAdapter
65.4k73 gold badges187 silver badges243 bronze badges
asked Apr 26, 2009 at 19:20

8 Answers 8

10

The code would be much cleaner if you use enum to represent rank and suite instead of char.

In fact, http://jcp.org/aboutJava/communityprocess/jsr/tiger/enum.html has a Card sample illustrates use of Enum

The relevant code bit is copied below

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;
 }
}
answered Apr 26, 2009 at 19:30

4 Comments

You could call One => Ace and Thirteen => King etc instead. ;)
The final standard was to use AOL-shouty-retard-case for enum instance names. Making Card immutable is a good idea.
Java's Enum intro page also gives a card example java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
Comparable is also a generic type. So your code should be something more like this: public class Card implements Comparable<Card>, java.io.Serializable { //... public int compareTo(Card c) { int rankCompare = rank.compareTo(c.rank); return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit); } }
9

One option is to implement the Comparable interface and then override 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.

answered Apr 26, 2009 at 19:24

2 Comments

Since a deck of cards has a natural sort order I would recommend using the Comparable interface over a separate Comparator class. Comparator classes should be used when an object doesn't have a natural sort order, like a Shoe class. Different people sort their shoes in different ways (by color, by size, by price). :-)
Bjorn: I would agree except that the role of the ace changes in many games (e.g., BJ and poker) so I would be careful about adding semantics to the cards.
4

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;
 }
 });
answered Apr 26, 2009 at 20:15

Comments

1

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.

answered Apr 26, 2009 at 19:27

Comments

1

A couple of shorter methods

public String toString() {
 return "" + rank + suit;
}
public boolean isValidCard(){
 return "HSDC".indexOf(suit) != -1 &&
 "A23456789TJQK".indexOf(rand) != -1;
}
answered Apr 26, 2009 at 19:33

Comments

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);
answered Apr 26, 2009 at 19:27

Comments

1
public class ClassName implements Comparable<Object> {
 // Variables --------------------------------------------
 private double comparedVariable; 
 // Constructor ------------------------------------------
 public ClassName (){}
 // Functions --------------------------------------------
 //returns the fuel weight
 public double getComparedVariable() {
 return comparedVariable;
 }
 // Overrides --------------------------------------------
 @Override
 public int compareTo(Object o) {
 ClassName classObject = (ClassName) o;
 if (this.comparedVariable> classObject.getComparedVariable())
 return 1; //make -1 to sort in decreasing order
 else if (this.comparedVariable< classObject.getComparedVariable())
 return -1;//make 1 to sort in decreasing order
 else
 return 0;
 }
}
Kerem Baydoğan
10.8k1 gold badge45 silver badges53 bronze badges
answered Jul 12, 2011 at 9:31

Comments

-1
public class player {
   String Fname = "";
  String Lname = "";
  ArrayList<Card> cards= new ArrayList<Card> ();
  public String getFname() {
    return Fname;
  }
  public void setFname(String Fname) {
    this.Fname = Fname;
  }
  public String getLname() {
    return Lname;
  }
  public void setLastname(String Lname) {
    this.Lname = Lname;
  }
  public ArrayList<Card> getCards() {
    return cards;
  }
  public void setCards(ArrayList<Card> cards) {
    this.cards = cards;
  }
  public player(String fname,String lname) {
    this.Fname = fname;
    this.Lname = lname;
  }
  
  public void AddCard(Card card){
    cards.add(card);
  }
  
  public void showCards(){
    System.out.println(""+Fname+" "+Lname+" holds the following cards");
    for (int i=0;i<cards.size();i++)
    {
      System.out.print(cards.get(i).toString());
    }
    System.out.println();
  }
  
  public void Sortcardsbyface()
  {
    for (int i = 0; i < cards.size() - 1; i++)
    {
      int j = i;
      for (int k = i + 1; k < cards.size(); k++)
      {
        Card c = new Card();
        if (c.toInt(cards.get(k).getFace()) < c.toInt(cards.get(j).getFace()))
        {
          j=k;
        }
      }
      Card temp = cards.get(j);
      cards.set(j,cards.get(i));
      cards.set(i,temp);
    }
    showCards();
  }
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pokegame;
/**
 *
 * @author admin
 */
public class Card {
   private String face;
  private char suit; 
  Card(char suit,String face) {
    this.suit = suit;
    this.face = face;
  }
  Card() {
    
  }
  public String getFace() {
    return face;
  }
  public void setFace(String face) {
    this.face = face;
  }
  public char getSuit() {
    return suit;
  }
  public void setSuit(char suit) {
    this.suit = suit;
  }
  
  public String toString(){
    return face+suit; 
  }
 
  
  public int toInt(String face){
    switch(face){
      case "A":
        return 1;
      case "J":
        return 11;
      case "Q":
        return 12;
      case "K":
        return 13;
      case "2":
        return 2;
      case "3":
        return 3;
      case "4":
        return 4;    
      case "5":
        return 5;    
      case "6":
        return 6;
      case "7":
        return 7;  
      case "8":
        return 8;  
      case "9":
        return 9;  
      case "10":
        return 10;  
        
        
        
        
      default:
        return 0;
    }
  }
  
}
answered Jun 26, 2015 at 11:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.