CS1027b Computer Science Fundamentals II

Lab 9

General lab instructions to help labs run smoothly

Upon completion of this lab, you should be able to use an iterator to step through the items in a collection. In this lab you will be using your PhoneTest.java from Lab 8. If you did not complete Lab 8, you can still complete this Lab. You will need to download all the files that were necessary for Lab 8 (see Lab 8 Exercise 0). You will also need to create your own data file as described in Lab 8, Exercise 1, step 2.

Exercise 1: Using an interator in an application

In this lab you are using your file PhoneTest.java from Lab 8 (you can use the same project that you used in Lab 8). You will add new code right after the code you inserted in Lab 8 to print the ordered list, to step through the list using an iterator and print part of the data in the ordered list.

Observe that list is of type ArrayOrderedList<Phone>, and is declared and created in PhoneTest.java by

ArrayOrderedList<Phone> list = new ArrayOrderedList<Phone>();
We can iterate through phoneList using the iterator method of the array implementation of the ListADT.
  1. Add import java.util.Iterator; at the top of your PhoneTest.java (so the compiler can use the Iterator interface).
  2. Add code, right after the code you wrote for Lab 8 that prints your ordered list of names and phone numbers, to iterate through your ordered list and print only the names (not the phone numbers). You will be using the iterator method of ArrayList. Hint see lecture notes on iterators, pages 17- 18.
  3. Run your PhoneTest.java to check that your new code works correctly.
  4. Now add code to iterate through your ordered list again and print only the phone numbers (not the names). Make sure you reset your iter variable (what happens if you don’t)?
  5. Run your PhoneTest.java to check that your new code works correctly.
  6. Answer the following questions:

Exercise 2: Using an iterator in a class definition

You will now write a different toString method for the ArrayList class: one that uses its iterator to step through the items in the list.

Exercise 3: Add an iterator method to the Stack implementations