Java Reference
In-Depth Information
You can get the default serialized output operation in a similar fashion by calling the
defaultWriteObject() method for the stream object that is passed to your output method.
Obviously, you must read back the data in exactly the same sequence as it was written, so the two
methods will have essentially mirror operations on the same sequence of data items.
Serialization Problems and Complications
For most classes and applications, serialization will work in a straightforward fashion. There are
situations that can cause confusion though. One such situation is when you want to write several
versions of the same object to a file. You need to take care to ensure the result is what you want.
Suppose you write an object to a file - a PolyLine object say. A little later in your code, you modify
the PolyLine object in some way, by moving a point perhaps, and you now write the same object to
the file again in its modified state. What happens? Does the file contain the two versions of the object?
The answer - perhaps surprisingly - is no. Let's explore this in a little more detail.
Try It Out - Serializing Variations on an Object
Let's start by defining a very simple serializable class that we can use in our example:
import java.io.Serializable;
public class Data implements Serializable {
private int value;
public Data(int init) {
value = init;
}
// Method to compare two Data objects
public boolean equals(Object obj) {
if(obj instanceof Data && ((Data)obj).value == value)
return true;
return false;
}
public void setValue(int val) {
value = val;
}
public int getValue() {
return value;
}
}
Objects of type Data have a single field of type int . Two Data objects are equal if their value fields
contain the same value. We can alter the value field for an object by calling its setValue() method
so we can easily create variations on the same object. Now we can write an example that will write
variations on a single instance of type Data to a file and then read them back:
Search WWH ::




Custom Search