Putting It All Together in a Sample Program
Let's construct a linked list abstract data type to manage a dynamic list of integer values. A list is a common and useful data structure. Unlike an array, a list doesn't have a predefined number of contents. You can add elements to it so long as the computer has enough memory to store them all! Additionally, you can add new items to, or remove them from, any point in the list without having to shuffle all the other elements around.
The lists in our sample datatype are made up of individual "nodes" of integers. Listing 1 contains the code for an individual "IntNode" object. Listing 2 strings this together to create an "IntList" object with methods to add or remove nodes and to list all its contents.
You will see that both classes implement the Serializable interface. Note that both classes need to be serializable, because the list is made up of nodesto save the list, Java needs to be able to save each node. Listing 3 contains a test program to run your list class through some exercises, including, of course, serialization! (See Figure 1 for the output from a sample run of the test program.)
First, build up a list (list1) with four data items. Then serialize your list to a disk file. Next, delete the first item from list1 and display its contents to the screen so you can verify that the list really has changed. Now, create a new list instance (list2) that has no items. Display its contents to prove this. Using serialization, load the saved data into list2 to populate it. Finally, display the contents of list2. You will see it has four data items, in the same order they appeared when you saved them from list1.
|Figure 1: Sample Run of the Test Program|
Persistent Object Implementation Made Easy
Java's support for object serialization makes implementing persistent objects extremely easy. By contrast, saving, and restoring every field of an object is complex and repetitive. You certainly could write your own serialization mechanism, but the simplicity Java provides in its serialization is hard to beat. Java serialization offers developers the following:
- It reduces the amount of time needed to save and restore object or application state.
- It eliminates the complexity involved with save and restore operations.
- It avoids the need to create a new file format.
- It makes travel over a network connection easier for objects.
With relatively little effort, you can apply serialization to a variety of tasks. Not only do applications benefit from serialization, but applets do also. Rather than specifying a long list of parameters or performing time-consuming initialization and parsing, an applet can simply reload a configuration object whose member variables contain all the information the applet needs to execute.
With a little imagination, serialization may just have a place in your next project!