Java Reference
In-Depth Information
Let us suppose, for example, that you wanted to improve the
Name
class
so that it didn't have to check whether the cached hash code was valid
each time. You could do this by setting
hash
in the constructor, instead
of lazily when it is asked for. But this causes a problem with serializa-
tionsince
hash
is transient it does not get written as part of serialization
(nor should it), so when you are deserializing you need to explicitly set
it. This means that you have to implement
readObject
to deserialize the
main fields and then set
hash
, which implies that you have to implement
writeObject
so that you know how the main fields were serialized.
public class BetterName implements Serializable {
private String name;
private long id;
private transient int hash;
private static long nextID = 0;
public BetterName(String name) {
this.name = name;
synchronized (BetterName.class) {
id = nextID++;
}
hash = name.hashCode();
}
private void writeObject(ObjectOutputStream out)
throws IOException
{
out.writeUTF(name);
out.writeLong(id);
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
name = in.readUTF();
id = in.readLong();
hash = name.hashCode();
}