// File: SObject.java
// Serializable objects
// Copyright (C) 2008 Gregory D. Weber

import java.util.*;
import java.io.*;

public class SObject implements Serializable {

    // Instance variables

    private Object left, right;
    
    // Comment out and compare
    public static final long serialVersionUID = 4L;

    // Constructor
    public SObject (Object ileft, Object iright) {
	left = ileft;
	right = iright;
    }

    // Other methods

    public String toString () {
	return "SObject (" + left.toString() + ", " + right.toString() + ")";
    }

    // Main method to test

    public static void main (String [] args)
	throws FileNotFoundException, ClassNotFoundException, IOException
    {
	File datafile = new File("sobject.data"); // look at this file!
	
	List<SObject> datalist;

	// Read list from file, or create a new empty list

	if (datafile.exists()) {
	    // open and read it
	    System.out.println("Reading " + datafile + "...");
	    ObjectInputStream istream =
		new ObjectInputStream(new FileInputStream(datafile));
	    datalist = (List<SObject>) istream.readObject();
	    istream.close();
	    System.out.println("Done");

	}

	else datalist = new ArrayList<SObject>();

	// Show the list

	System.out.println("Here is the list:");
	for (SObject so : datalist) 
	    System.out.println(so);
	System.out.println("END OF LIST\n");

	// Append to the list
	Scanner stdin = new Scanner(System.in);
	System.out.print("Add left: ");
	String aleft = stdin.nextLine();
	System.out.print("Add right: ");
	String aright = stdin.nextLine();
	datalist.add(new SObject(aleft, aright));
	
	// (Re-)write the file
	System.out.println("Writing " + datafile + "...");
	ObjectOutputStream ostream =
	    new ObjectOutputStream(new FileOutputStream(datafile));
	ostream.writeObject(datalist);
	ostream.close();

	System.out.println("Done");

    }

}

	
