// Notes on Serializable Data. import java.io.*; // Consider the following simple linked list class: class cell { int x; cell next; } /* You should know that 'next' is a pointer, not another cell, because that would mean an infinitely large structure. But what if we wanted transport such a data structure over a network connection to another computer? The pointer is a memory address, and it won't be pointing to the same thing on the remote machine: clearly we can't just send the pointer. The same applies if we wanted to store a list to a file and reload later. Memory would have changed when we reload it and the pointer will no longer be valid. In order to transport such a data structure, we must "serialize" it at runtime. This means we must flatten the structure by unrolling the next pointer until it reaches null. Java will do this automatically if you mark the class as implementing the interface java.io.Serializable: */ class node implements Serializable { int x; node next; public node(int y, node n) { x=y; next=n; } } /* Implementing Serializable, however, doesn't mean that we must implement some particular function inside our class. This interface is just a marker that tells Java what to do with it if we transport it at runtime. But not all classes can be marked Serializable: */ class someclass implements Serializable { // cell n; // WILL NOT COMPILE node m; // will compile because node is also Serializable } /* In order to be marked Serializable, all the instance variables of the class must also be of Serializable type. All primitive types (int, boolean, etc) are serializable. Many of Java's built-in class types, Integer, String, etc are also serializable. Arrays are serializable if its contents are serializable. The following class is also serializable, and you should understand why: */ class polynode implements Serializable { T x; polynode next; } public class Serial { public static void main(String[] args) { node L = new node(2,new node(3, new node(5,new node(7,null)))); node M=null; try { java.io.ObjectOutputStream obout = new ObjectOutputStream(new FileOutputStream("savedlist")); obout.writeObject(L); obout.close(); ObjectInputStream obin = new ObjectInputStream(new FileInputStream("savedlist")); M = (node) obin.readObject(); System.out.println(L.x==M.x && L.next.x==M.next.x); // true } //try catch (IOException ie) { System.out.println(ie); } catch (ClassNotFoundException cnfe) {System.out.println("wrong class");} }//main }