Monday, April 18, 2011

Collections and serializablity

Collections don't extend Serializable interface but its implementations do.Similar note go for other interfaces like sets, lists.

Set doesn't extends Serializable interface but its implementations (HashSet, TreeSet, EnumSet) implements Serializable interface and so contains methods writeObject and readObject to save or reconstitute the state of Set (HashSet, TreeSet, EnumSet) instance to/from a stream. When you serialize this instance, writeObject and readObject methods will be called.

Collections like Vector and Hashtable both implements Serializable and have been designed for serialization.

One thing to keep in mind is to watch out for is, that in order to serialize a collection like Vector or Hashtable, you must also be able to serialize all of the objects contained in these collections. Otherwise, the collection would not be able to be completely restored. Your program will throw a NotSerializableException unless all objects stored in the Vector or Hashtable are also serializable.

Eg.
If your class implements Serializable and all of its members are serializable, then the object can be serialized correctly. Example:

public class Person implements Serializable {
    private String name;
    private Collection<Integer> medals = new ArrayList<Integer>();
}


As long as medals's instance is serializable (such as ArrayList), and its members are serializable (in this case Integers) , then the object will serialize.



No comments:

Post a Comment

Chitika