Java Reference
In-Depth Information
return;
default:
System.out.println("Invalid selection, try again.");
break;
}
}
}
}
How It Works
The first changes here are an updated prompt for input and a new case in the
switch
to list the entries
in the phone book. The other change is to call the
save()
method to write the map that stores the
phone book to a file before ending the program.
Be aware of the default
hashCode()
method in the
Object
class when storing maps.
The hash codes are generated from the address of the object, and getting a key object
back from a file in exactly the same place in memory is about as likely as finding hairs
on a frog. The result is that the hashcode generated from the key when it is read back
will be different from when it was originally produced, so you will never find the entry
in the map to which it corresponds.
If we override the default
hashCode()
method then our hash codes are produced
from the data members of the key objects, so they are always the same regardless of
where the key objects are stored in memory.
The first time you run this version of
TryPhoneBook
it will create a new file and store the entire phone
book in it. On subsequent occasions the
PhoneBook
constructor will read from the file, so all the
previous entries are available.
In the next chapter we'll move on to look at some of the other components from the
java.util
package.
Summary
All of the classes in this chapter will be useful sooner or later when you're writing your own Java
programs. We'll be applying many of them in examples throughout the remainder of the topic.
The important elements we've covered are:
You can use a
Vector
object as a kind of flexible array that expands automatically to
accommodate any number of objects stored.
❑
The
Stack
class is derived from the
Vector
class and implements a pushdown stack.
❑
The
HashMap
class defines a hash map in which objects are stored based on an associated key.
❑