1 import java.util.*; 2 3 public class Customer { 4 private String _name; 5 private ArrayList _rentals = new ArrayList(); 6 7 public Customer(String name) { 8 _name = name; 9 } 10 11 public void addRental(Rental arg) { 12 _rentals.add(arg); 13 } 14 15 public String getName() { 16 return _name; 17 } 18 19 // How many times do we traverse the rentals ArrayList? 20 // Does it matter? 21 public String statement() 22 { 23 StringBuffer buffer = new StringBuffer(_rentals.size() * 25); 24 buffer.append("Rental Record for " + getName() + "\n"); 25 for(int i = 0, n = _rentals.size(); i < n; i++){ 26 Rental rental = (Rental) _rentals.get(i); 27 //show figures for this rental 28 buffer.append("\t"); 29 buffer.append(rental.getMovie().getTitle()); 30 buffer.append("\t"); 31 buffer.append(rental.getCharge()); 32 buffer.append("\n"); 33 } 34 //add footer lines 35 buffer.append("Amount owed is " + getTotalCharge() + "\n"); 36 37 buffer.append("You earned " + 38 getTotalFrequentRenterPoints() + 39 " frequent renter points"); 40 return buffer.toString(); 41 } 42 43 private double getTotalCharge() 44 { 45 double result = 0; 46 for(int i = 0, n = _rentals.size(); i < n; i++) 47 result += ((Rental) _rentals.get(i)).getCharge(); 48 return result; 49 } 50 51 private int getTotalFrequentRenterPoints() 52 { 53 int result = 0; 54 for(int i = 0, n = _rentals.size(); i < n; i++) 55 result += ((Rental)_rentals.get(i)).getFrequentRenterPoints(); 56 return result; 57 } 58 59 private static long stressTest(Customer customer, Rental rental, int numberRentals) 60 { 61 for(int i = 0; i < numberRentals; i++) 62 customer.addRental(rental); 63 long startTime = System.currentTimeMillis(); 64 double totalCharge = customer.getTotalCharge(); 65 String statement = customer.statement(); 66 return System.currentTimeMillis() - startTime; 67 } 68 69 public static void main(String argv[]) 70 { 71 Customer harry = new Customer("Harry"); 72 Movie movie = new Movie("Gone With The Wind", Movie.REGULAR); 73 Rental rental = new Rental(movie, 3); 74 harry.addRental(rental); 75 System.out.println(harry.statement()); 76 Customer tom = new Customer("Tom"); 77 // Suppose we have 1000000 rentals. How long will it take 78 // to compute the total chare? 79 int numberRentals = 1000000; 80 long timeToCompute = stressTest(tom, rental, 1000000); 81 System.out.println("time elapsed for " + numberRentals + 82 " rentals = " + timeToCompute); 83 } 84 } 85 // Output: 86 // $ java -classpath . Customer 87 // Rental Record for Harry 88 // Gone With The Wind 3.5 89 // Amount owed is 3.5 90 // You earned 1 frequent renter points 91 // time elapsed for 1000000 = 330, totalCharge is 3500000.0