算法Sedgewick第四版-第1章基础-003一封装交易对象

1.

  1 package ADT;
  2
  3 /******************************************************************************
  4  *  Compilation:  javac Transaction.java
  5  *  Execution:    java Transaction
  6  *  Dependencies: StdOut.java
  7  *
  8  *  Data type for commercial transactions.
  9  *
 10  ******************************************************************************/
 11
 12 import java.util.Arrays;
 13 import java.util.Comparator;
 14
 15 import algorithms.util.StdOut;
 16
 17
 18 /**
 19  *  The <tt>Transaction</tt> class is an immutable data type to encapsulate a
 20  *  commercial transaction with a customer name, date, and amount.
 21  *  <p>
 22  *  For additional documentation,
 23  *  see <a href="http://algs4.cs.princeton.edu/12oop">Section 1.2</a> of
 24  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 25  *
 26  *  @author Robert Sedgewick
 27  *  @author Kevin Wayne
 28  */
 29 public class Transaction implements Comparable<Transaction> {
 30     private final String  who;      // customer
 31     private final Date    when;     // date
 32     private final double  amount;   // amount
 33
 34
 35     /**
 36      * Initializes a new transaction from the given arguments.
 37      *
 38      * @param  who the person involved in this transaction
 39      * @param  when the date of this transaction
 40      * @param  amount the amount of this transaction
 41      * @throws IllegalArgumentException if <tt>amount</tt>
 42      *         is <tt>Double.NaN</tt>, <tt>Double.POSITIVE_INFINITY</tt>,
 43      *         or <tt>Double.NEGATIVE_INFINITY</tt>
 44      */
 45     public Transaction(String who, Date when, double amount) {
 46         if (Double.isNaN(amount) || Double.isInfinite(amount))
 47             throw new IllegalArgumentException("Amount cannot be NaN or infinite");
 48         this.who    = who;
 49         this.when   = when;
 50         if (amount == 0.0) this.amount = 0.0;  // to handle -0.0
 51         else               this.amount = amount;
 52     }
 53
 54     /**
 55      * Initializes a new transaction by parsing a string of the form NAME DATE AMOUNT.
 56      *
 57      * @param  transaction the string to parse
 58      * @throws IllegalArgumentException if <tt>amount</tt>
 59      *         is <tt>Double.NaN</tt>, <tt>Double.POSITIVE_INFINITY</tt>,
 60      *         or <tt>Double.NEGATIVE_INFINITY</tt>
 61      */
 62     public Transaction(String transaction) {
 63         String[] a = transaction.split("\\s+");
 64         who    = a[0];
 65         when   = new Date(a[1]);
 66         double value = Double.parseDouble(a[2]);
 67         if (value == 0.0) amount = 0.0;  // convert -0.0 0.0
 68         else              amount = value;
 69         if (Double.isNaN(amount) || Double.isInfinite(amount))
 70             throw new IllegalArgumentException("Amount cannot be NaN or infinite");
 71     }
 72
 73     /**
 74      * Returns the name of the customer involved in this transaction.
 75      *
 76      * @return the name of the customer involved in this transaction
 77      */
 78     public String who() {
 79         return who;
 80     }
 81
 82     /**
 83      * Returns the date of this transaction.
 84      *
 85      * @return the date of this transaction
 86      */
 87     public Date when() {
 88         return when;
 89     }
 90
 91     /**
 92      * Returns the amount of this transaction.
 93      *
 94      * @return the amount of this transaction
 95      */
 96     public double amount() {
 97         return amount;
 98     }
 99
100     /**
101      * Returns a string representation of this transaction.
102      *
103      * @return a string representation of this transaction
104      */
105     @Override
106     public String toString() {
107         return String.format("%-10s %10s %8.2f", who, when, amount);
108     }
109
110     /**
111      * Compares two transactions by amount.
112      *
113      * @param  that the other transaction
114      * @return { a negative integer, zero, a positive integer}, depending
115      *         on whether the amount of this transaction is { less than,
116      *         equal to, or greater than } the amount of that transaction
117      */
118     public int compareTo(Transaction that) {
119         if      (this.amount < that.amount) return -1;
120         else if (this.amount > that.amount) return +1;
121         else                                return  0;
122     }
123
124     /**
125      * Compares this transaction to the specified object.
126      *
127      * @param  other the other transaction
128      * @return true if this transaction is equal to <tt>other</tt>; false otherwise
129      */
130     @Override
131     public boolean equals(Object other) {
132         if (other == this) return true;
133         if (other == null) return false;
134         if (other.getClass() != this.getClass()) return false;
135         Transaction that = (Transaction) other;
136         return (this.amount == that.amount) && (this.who.equals(that.who))
137                                             && (this.when.equals(that.when));
138     }
139
140
141     /**
142      * Returns a hash code for this transaction.
143      *
144      * @return a hash code for this transaction
145      */
146     public int hashCode() {
147         int hash = 17;
148         hash = 31*hash + who.hashCode();
149         hash = 31*hash + when.hashCode();
150         hash = 31*hash + ((Double) amount).hashCode();
151         return hash;
152     }
153
154     /**
155      * Compares two transactions by customer name.
156      */
157     public static class WhoOrder implements Comparator<Transaction> {
158
159         @Override
160         public int compare(Transaction v, Transaction w) {
161             return v.who.compareTo(w.who);
162         }
163     }
164
165     /**
166      * Compares two transactions by date.
167      */
168     public static class WhenOrder implements Comparator<Transaction> {
169
170         @Override
171         public int compare(Transaction v, Transaction w) {
172             return v.when.compareTo(w.when);
173         }
174     }
175
176     /**
177      * Compares two transactions by amount.
178      */
179     public static class HowMuchOrder implements Comparator<Transaction> {
180
181         @Override
182         public int compare(Transaction v, Transaction w) {
183             if      (v.amount < w.amount) return -1;
184             else if (v.amount > w.amount) return +1;
185             else                          return  0;
186         }
187     }
188
189
190     /**
191      * Unit tests the <tt>Transaction</tt> data type.
192      */
193     public static void main(String[] args) {
194         Transaction[] a = new Transaction[4];
195         a[0] = new Transaction("Turing   6/17/1990  644.08");
196         a[1] = new Transaction("Tarjan   3/26/2002 4121.85");
197         a[2] = new Transaction("Knuth    6/14/1999  288.34");
198         a[3] = new Transaction("Dijkstra 8/22/2007 2678.40");
199
200         StdOut.println("Unsorted");
201         for (int i = 0; i < a.length; i++)
202             StdOut.println(a[i]);
203         StdOut.println();
204
205         StdOut.println("Sort by date");
206         Arrays.sort(a, new Transaction.WhenOrder());
207         for (int i = 0; i < a.length; i++)
208             StdOut.println(a[i]);
209         StdOut.println();
210
211         StdOut.println("Sort by customer");
212         Arrays.sort(a, new Transaction.WhoOrder());
213         for (int i = 0; i < a.length; i++)
214             StdOut.println(a[i]);
215         StdOut.println();
216
217         StdOut.println("Sort by amount");
218         Arrays.sort(a, new Transaction.HowMuchOrder());
219         for (int i = 0; i < a.length; i++)
220             StdOut.println(a[i]);
221         StdOut.println();
222     }
223
224 }
时间: 2024-08-08 19:53:46

算法Sedgewick第四版-第1章基础-003一封装交易对象的相关文章

算法Sedgewick第四版-第1章基础-004一封装输入(可以文件,jar包里的文件或网址)

1. 1 package algorithms.util; 2 3 /****************************************************************************** 4 * Compilation: javac In.java 5 * Execution: java In (basic test --- see source for required files) 6 * Dependencies: none 7 * 8 * Read

算法Sedgewick第四版-第1章基础-004一封装输出(文件)

1. 1 package algorithms.util; 2 3 /****************************************************************************** 4 * Compilation: javac Out.java 5 * Execution: java Out 6 * Dependencies: none 7 * 8 * Writes data of various types to: stdout, file, or

算法Sedgewick第四版-第1章基础-001递归

一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归,因为递归代码比相应的非递归代码更加简洁优雅.易懂.下面这种实现中的注释就言简意赅地说明了代码的作用.我们可以用数学归纳法证明这段注释所解释的算法的正确性.我们会在 3.1 节中展开这个话题并为二分查找提供一个这样的证明.编写递归代码时最重要的有以下三点.? 递归总有一个最简单的情况——方法的第一条语

算法Sedgewick第四版-第1章基础-008一用数组实现固定长度的栈

1 package algorithms.ADT; 2 3 /****************************************************************************** 4 * Compilation: javac FixedCapacityStackOfStrings.java 5 * Execution: java FixedCapacityStackOfStrings 6 * Dependencies: StdIn.java StdOut.

算法Sedgewick第四版-第1章基础-1.4 Analysis of Algorithms-005计测试算法

1. 1 package algorithms.analysis14; 2 3 import algorithms.util.StdOut; 4 import algorithms.util.StdRandom; 5 6 /****************************************************************************** 7 * Compilation: javac DoublingTest.java 8 * Execution: jav

算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)

一.介绍 1.时间和空间复杂度 运行过程 2.特点: (1)对于已排序或接近排好的数据,速度很快 (2)对于部分排好序的输入,速度快 二.代码 1 package algorithms.elementary21; 2 3 /****************************************************************************** 4 * Compilation: javac Insertion.java 5 * Execution: java I

算法Sedgewick第四版-第1章基础-018一解决不能声明泛型数组的两咱方法(强转或反射)

1. 1 /****************************************************************************** 2 * Compilation: javac ResizingArrayStackWithReflection.java 3 * Execution: java ResizingArrayStackWithReflection < input.txt 4 * Dependencies: StdIn.java StdOut.jav

算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)

一. 1. 2. 3. 二.代码 1 package algorithms.mergesort22; 2 3 import algorithms.util.StdIn; 4 import algorithms.util.StdOut; 5 6 /****************************************************************************** 7 * Compilation: javac MergeBU.java 8 * Executio

算法Sedgewick第四版-第1章基础-1.3Bags, Queues, and Stacks-001可变在小的

1. package algorithms.stacks13; /****************************************************************************** * Compilation: javac ResizingArrayBag.java * Execution: java ResizingArrayBag * Dependencies: StdIn.java StdOut.java * * Bag implementatio