01: import java.util.ArrayList;
02: import java.util.Collections;
03: import java.util.Comparator;
04: 
05: /**
06:    A purse holds a collection of coins.
07: */
08: public class Purse
09: {
10:    /**
11:       Constructs an empty purse.
12:    */
13:    public Purse()
14:    {
15:       coins = new ArrayList();
16:    }
17: 
18:    /**
19:       Add a coin to the purse.
20:       @param aCoin the coin to add
21:    */
22:    public void add(Coin aCoin)
23:    {
24:       coins.add(aCoin);
25:    }
26: 
27:    /**
28:       Returns a string describing the purse contents,
29:       sorted by coin value.
30:       @return the string describing the purse contents
31:    */
32:    public String toString()
33:    {
34:       // sort the coins first
35:       class CoinComparator implements Comparator
36:       {
37:          public int compare(Object firstObject, Object secondObject)
38:          {
39:             Coin first = (Coin)firstObject;
40:             Coin second = (Coin)secondObject;
41:             if (first.getValue() < second.getValue()) return -1;
42:             if (first.getValue() == second.getValue()) return 0;
43:             return 1;
44:          }       
45:       }
46: 
47:       Comparator comp = new CoinComparator();
48:       Collections.sort(coins, comp);
49: 
50:       String r = "Purse[coins=";
51:       for (int i = 0; i < coins.size(); i++)
52:       {
53:          if (i > 0) r = r + ",";
54:          r = r + coins.get(i);
55:       }
56:       return r + "]";
57:    }
58: 
59:    private ArrayList coins;
60: }
61: