THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

When the serialized hash map is deserialized, the two analogous entries in the new copy of the hash map will
have references to a single copy of the rose.jpg object, not references to two separate copies of
rose.jpg.[2]


[2] The first key field is the word "rose" in Tibetan.

Sometimes, however, sharing objects in this way is not what is desired. In that case you can use
ObjectOutputStream's writeUnshared method to write the object as a new distinct object, rather
than using a reference to an existing serialization of that object. Any object written into the graph by
writeUnshared will only ever have one reference to it in the serialized data. The readUnshared
method of ObjectInputStream reads an object that is expected to be unique. If the object is actually a
reference to an existing deserialized object then an ObjectStreamException is thrown; similarly, if the
deserialization process later tries to create a second reference to an object returned by readUnshared, an
ObjectStreamException is thrown. These uniqueness checks only apply to the actual object passed to
writeUnshared or read by readUnshared, not to any objects they refer to.


20.8.2. Making Your Classes Serializable


When an ObjectOutputStream writes a serialized object, the object must implement the
Serializable marker interface. This marker interface declares that the class is designed to have its objects
serialized.


Being serializable can be quite simple. The default serialization process is to serialize each field of the object
that is neither TRansient nor static. Primitive types and strings are written in the same encoding used
by DataOutputStream; objects are serialized by calling writeObject. With default serialization, all
serialized fields that are object references must refer to serializable object types. Default serialization also
requires either that your superclass have a no-arg constructor (so that deserialization can invoke it) or that it
also be Serializable (in which case declaring your class to implement Serializable is redundant but
harmless). For most classes this default serialization is sufficient, and the entire work necessary to make a
class serializable is to mark it as such by declaring that it implements the Serializable interface:


public class Name implements java.io.Serializable {
private String name;
private long id;
private transient boolean hashSet = false;
private transient int hash;
private static long nextID = 0;


public Name(String name) {
this.name = name;
synchronized (Name.class) {
id = nextID++;
}
}


public int hashCode() {

Free download pdf