Lab 4: Java Class Library: LinkedList and ListIterator
Lab Objectives
- Use the LinkedList class from the
Java class library
- Use the ListIterator interface from
the Java class library
Lab References
- Chapter 4: Lists in general
- Chapter 8: Iterators in general and the LinkedList
class from the Java class library.
Problem Description
The standard Java package java.util
contains the class LinkedList and the
interface ListIterator. The entries in the
list begin at position 0. The method iterator
in the LinkedList class returns an Iterator
that implements the ListIterator
interface.
For this lab display the results using System.out.
The directions can be found as comments in MyProgram.java.
Files Required
Lab Exercise
- Review the documentation for LinkedList
and ListIterator. It can be found at
http://java.sun.com/j2se/1.4/docs/api/.
You will be using the methods listed.
- Import the classes in the package java.util.
- Create an instance of LinkedList.
- Add 5 entries to the list so that it contains Ann, Bart, Carl,
Dirk, and Zak.
- Display the list on one line using a loop and ADT list
methods.
- Display the list using one println.
- Create a ListIterator object for the
list.
- Display the list on one line using the iterator.
- Restore the iterator to the first item in the list.
- Retrieve and display the first item in the iteration, then
advance the iterator to the next item.
- Advance the iterator to the end of the list without displaying
anything; do not use the length of the list.
- Display the last item in the list.
- Move back to the beginning of the list without displaying
anything; do not use the length of the list.
- Display the first item in the list.
- Advance the iterator to the end of the list without displaying
anything.
- Advance the iterator.
What happens?
- Comment out the code from the previous step. Advance the
iterator within a try block; catch the
exception, display a message and set the iterator back to the
beginning of the list.
- What do nextIndex and previousIndex
return?
- Move the iterator to the third item in the list; if you were
to execute next(), the third item would
be returned and the iterator would advance to the 4th item.
- Add the string "New" to the list.
Where is it inserted relative to the current item in the
iteration?
- Remove the current item.
What happens?
- Display the current item in the list without advancing the
iteration in 2 ways, as follows:
- Using only iterator methods
- Using an iterator method and list methods
- Advance the iterator and remove the current item.
Which one is removed?
- Move the iterator back and remove the current item.
Which one is removed?
- Move the iterator to the first item in the list and change it
to "First".