Java Reference
In-Depth Information
Example 9−2: IntList.java (continued)
out.defaultWriteObject();
// Then write it out normally.
}
/** Compute the transient size field after deserializing the array */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
// Read the array normally.
size = data.length;
// Restore the transient field.
}
/**
* Does this object contain the same values as the object o?
* We override this Object method so we can test the class.
**/
public boolean equals(Object o) {
if (!(o instanceof IntList)) return false;
IntList that = (IntList) o;
if (this.size != that.size) return false;
for(int i = 0; i < this.size; i++)
if (this.data[i] != that.data[i]) return false;
return true;
}
/** A main() method to prove that it works */
public static void main(String[] args) throws Exception {
IntList list = new IntList();
for(int i = 0; i < 100; i++) list.add((int)(Math.random()*40000));
IntList copy = (IntList)Serializer.deepclone(list);
if (list.equals(copy)) System.out.println("equal copies");
Serializer.store(list, new File("intlist.ser"));
}
}
Externalizable Classes
The
Externalizable
interface extends
Serializable
and defines the
write-
External()
and
readExternal()
methods. An
Externalizable
object may be seri-
alized as other
Serializable
objects are, but the serialization mechanism calls
writeExternal()
and
readExternal()
to perform the serialization and deserializa-
tion. Unlike the
readObject()
and
writeObject()
methods in Example 9-2, the
readExternal()
and
writeExternal()
methods can't call the
defaultReadOb-
ject()
and
defaultWriteObject()
methods: they must read and write the com-
plete state of the object by themselves.
It is useful to declare an object
Externalizable
when the object already has an
existing file format or when you want to accomplish something that is simply not
possible with the standard serialization methods. Example 9-3 defines the
Com-
pactIntList
class, an
Externalizable
subclass of the
IntList
class from the pre-
vious example.
CompactIntList
makes the assumption that it is typically used to
store many small numbers; it implements
Externalizable
so it can define a serial-
ized form that is more compact than the format used by
ObjectOutputStream
and
ObjectInputStream
.