Java Reference
In-Depth Information
return;
default:
System.out.println("Invalid selection, try again.");
break;
}
}
}
}
Directory "TryPhoneBook 2"
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.
WARNING Beware of the default hashCode() method in the Object class when
storing maps in a file. As you know, the hashcodes are generated from the address
of the object, so the hashcode for a key is entirely dependent on where it is stored in
memory. Getting a key back from a file in exactly the same place in memory where
it was originally stored is about as likely as finding hairs on a frog. The result is
that when you read a map back from a file, the hashcode generated from a key you
now use to access the map is different from what was originally produced when you
stored the object with the key, so you will never find the entry in the map to which it
corresponds.
Thereisasolution totheproblem.Youmustoverride thedefault hashCode() meth-
od so that the hashcodes for keys are produced from the data members of the key
objects.Thisensuresthatthehashcodeforagivenkeyisalwaysthesame.The Per-
son class does exactly this by overriding the hashCode() method.
The first time you run TryPhoneBook2 it creates a new file and stores the entire phone book in it. On
subsequent occasions the PhoneBook constructor reads from the file, so all the previous entries are avail-
able.
In the next chapter you 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.
You apply many of them in examples throughout the remainder of the topic. Collection classes have been
implemented in other languages such as C++, so the concepts you have learned here about ways of storing
and organizing objects applicability are applicable in other situations.
Search WWH ::




Custom Search