import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class PersistentCollection<E> extends MyList<E> {

  private ObjectOutputStream oos;
  private String fileName;

  public PersistentCollection(String name) {
    try {
      fileName = name;
      oos = new ObjectOutputStream(new FileOutputStream(new File(fileName)));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected void finalize() throws Throwable {
    try {
      oos.close();
    } finally {
      super.finalize();
    }
  }

  public void add(E e) {
    try {
      oos.writeObject(e);
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    super.add(e);
  }

  public void set(int i, E e) {
    try {
      oos.close();
      oos = new ObjectOutputStream(new FileOutputStream(new File(fileName)));
      super.set(i, e);
      for (E aux : this) {
        oos.writeObject(aux);
      }
    } catch (Exception e1) {
      e1.printStackTrace();
    }
  }

  public E get(int i) {
    return super.get(i);
  }

  public void printPersistentData() {
    try {
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
          new File(fileName)));
      for (Object e = ois.readObject(); e != null; e = ois.readObject()) {
        System.out.print(e + " ");
      }
      ois.close();
    } catch (EOFException eof) {
      System.out.println();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
