001package algs12; 002import stdlib.*; 003 004public class XCardSimple implements Comparable<XCardSimple> { 005 public static enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } 006 public static enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } 007 008 public final Rank rank; 009 public final Suit suit; 010 public XCardSimple (Rank r, Suit s) { this.rank = r; this.suit = s; } 011 public String toString () { return rank + " of " + suit; } 012 public int compareTo (XCardSimple that) { 013 if (this.suit.compareTo (that.suit) < 0) return -1; 014 if (this.suit.compareTo (that.suit) > 0) return +1; 015 if (this.rank.compareTo (that.rank) < 0) return -1; 016 if (this.rank.compareTo (that.rank) > 0) return +1; 017 return 0; 018 } 019 public boolean equals (Object that) { 020 if (that == null) 021 return false; 022 if (this.getClass() != that.getClass()) 023 return false; 024 // This does the right thing but is inefficient. 025 // Since equals may be used more than compareTo, there is usually a separate implementation. 026 return 0 == this.compareTo ((XCardSimple) that); 027 } 028 029 public static void main (String[] args) { 030 Suit s1 = Suit.CLUBS; 031 //Suit s2 = new Suit(); 032 033 XCardSimple c1 = new XCardSimple(Rank.ACE, Suit.SPADES); 034 XCardSimple c2 = new XCardSimple(Rank.ACE, Suit.SPADES); 035 StdOut.println (c1 + (c1.equals(c2) ? " equals " : " does not equal ") + c2); 036 } 037}