Card.java Source code

Java tutorial

Introduction

Here is the source code for Card.java

Source

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Card implements Comparable<Card> {

    static enum Suit {
        CLUBS, DIAMONDS, HEARTS, SPADES
    }

    static enum Rank {
        DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
    }

    public Suit suit;
    public Rank rank;

    public Card(Rank ranker, Suit suiter) {
        rank = ranker;
        suit = suiter;
    }

    @Override
    public int compareTo(Card o) {
        int rankCom = rank.compareTo(o.rank);
        return rankCom != 0 ? rankCom : suit.compareTo(o.suit);
    }

    public String toString() {
        return suit.toString() + " " + rank.toString();
    }
}

public class Main {
    public static void main(String args[]) {
        List<Card> lc = new ArrayList<Card>();
        lc.add(new Card(Card.Rank.SIX, Card.Suit.CLUBS));
        lc.add(new Card(Card.Rank.TEN, Card.Suit.CLUBS));
        lc.add(new Card(Card.Rank.SIX, Card.Suit.HEARTS));
        lc.add(new Card(Card.Rank.ACE, Card.Suit.HEARTS));

        System.out.println(lc);
        Collections.sort(lc);
        System.out.println(lc);
    }
}