ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
22. Phone Book Application
Answer:
The program fragment works.
Double total, meal, tax;
meal = 20.00; // autobox the 20.0
tax = meal*0.12; // unbox meal, do the math, autobox the product
total = meal+tax; // unbox meal and tax, do the math, autobox the total
System.out.println("Total Cost: " + total ); // unbox total, convert to String, concatenate
Even though this works, it is not sensible code. There is no reason to use the Double
wrapper class here.
Phone Book Application
ArrayList
s are especially convenient when you want to maintain a list of your own object types. Let us develop an application that maintains a phone book. Each entry in the phone book contains a name
and a number
along with various methods.
class Entry { private String name; private String number; // constructor public Entry( String n, String num ) { name = n; number = num; } // various methods . . . } |
The program will maintain an ArrayList
of phone book entries. The user will type in a name and get a phone number.
Enter name --> Hal
Name: Hal; Number: 789-1234
Enter name --> Amy
Name: Amy; Number: 123-4567
Enter name --> quit
Question 22:
Suggest some methods that will be useful for
Entry
.