Java Reference
In-Depth Information
Aswellasprovidingan add() methodtostore ToDo instancesinthe ToDoArray
instance, ToDoList provides hasMoreElements() and nextElement() meth-
odstoiterateoverandreturnthestoredinstances. Listing3-9 demonstratesthesemeth-
ods.
Listing 3-9. Creating and iterating over a ToDoList of ToDo instances
class NSMCDemo
{
public static void main(String[] args)
{
ToDoList toDoList = new ToDoList();
toDoList.add(new ToDo("#1", "Do laundry."));
toDoList.add(new ToDo("#2", "Buy groceries."));
toDoList.add(new ToDo("#3", "Vacuum apartment."));
toDoList.add(new ToDo("#4", "Write report."));
toDoList.add(new ToDo("#5", "Wash car."));
while (toDoList.hasMoreElements())
System.out.println(toDoList.nextElement());
}
}
Compileallthreelistings( javac NSMCDemo.java or javac *.java )andrun
the application ( java NSMCDemo ). You will then observe the following output:
Name = #1, Desc = Do laundry.
Name = #2, Desc = Buy groceries.
Name = #3, Desc = Vacuum apartment.
Name = #4, Desc = Write report.
Name = #5, Desc = Wash car.
Java's class library presents many examples of nonstatic member classes. For ex-
ample,the java.util package's HashMap classdeclaresprivate HashIterator ,
ValueIterator , KeyIterator ,and EntryIterator classesforiteratingover
a hashmap's values, keys, and entries. (I will discuss HashMap in Chapter 5 . )
Note Code within an enclosed class can obtain a reference to its enclosing class
instance by qualifying reserved word this with the enclosing class's name and the
memberaccessoperator.Forexample,ifcodewithin accessEnclosingClass()
Search WWH ::




Custom Search