Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Serializing Vector

A vector is only serializable if all the elements are also serializable. Or, you'll get a NotSerializableException thrown. import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Enumeration; import java.util.Vector; public class MainClass {   public static void main (String args[]) throws Exception {     Vector v = new Vector(Arrays.asList("a","b","c"));     ByteArrayOutputStream baos = new ByteArrayOutputStream();     ObjectOutputStream oos = new ObjectOutputStream(baos);     oos.writeObject(v);     oos.close();     ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());     ObjectInputStream ois = new ObjectInputStream(bais);     Vector v2 = (Vector)ois.readObject();     Enumeration e = v.elements();     while (e.hasMoreElements()) {       System.out.println(e.nextElement());     }   } } a b c