writeObject() with serialization

Posted on 2009-02-09
Last Modified: 2013-11-23
My assignment (not asking you to do this, just point me in the right direction, the description is longer than the actual question) is to create a Binary Tree (done), and write the output to a file name (out.dat). The assignment is for one of the binary trees to use serialization to show how this code will create a smaller out.dat file than using the default writeObject command which will be used in the other binary Tree file. To do this we need to write our own writeObject/readObject method.

I think I have the read object method but will include it for a complete picture.

The example we are working off of is a Linked List. Below is the write/readObject code used in class example,

private void writeObject(ObjectOutputStream s) throws IOException
{ System.out.println("call specialized writer");
for (Iterator i = _v.iterator(); i.hasNext(); )

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{ System.out.println("call specialized reader");
_v = new LinkedList();
int size = in.readInt();
for (int i = 0; i<size; i++)

Then in the test file we use the following code to write out.dat, which uses the above code for write and readObject.

ObjectOutputStream os
= new ObjectOutputStream
(new FileOutputStream("out.dat"));

ObjectInputStream in
= new ObjectInputStream
(new FileInputStream("out.dat"));
IntListSerializable V = (IntListSerializable) in.readObject();
My problem comes in for the write method. First I am not sure how to return the next value in my tree with out doing the inorder recursive traversal.

In my tree I have the following methods...
Lookup() which is a boolean, Insert, size(), printTree, printPostOrder

Could I do a recursive next() function where it traverses similar to printTree, except use next and no print functions?

Should I just create a tree in my class source code?

BinaryTree someTree = new BinaryTree();

Then on the readObject in the testing file, which reads from the writeObject I am trying to put together above...

This is the example we are given to model off of...
ObjectInputStream in = new ObjectInputStream (new FileInputStream("out.dat"));
IntListSerializable V = (IntListSerializable) in.readObject();

Do I just do something like the following?
BinaryTree X = (BinaryTree)in.readObject();
Node X = (Node)in.readObject();
public void printTree() {




private void printTree(Node node) {

if (node == null) 


// left, node itself, right


System.out.print( + " ");



This was I could do something like ...

private void writeObject(ObjectOutputStream s) throws IOException 

{ System.out.println("call specialized writer");

s.writeInt( ???.size()); 

for (i = 0; i < size; i++)

s.writeInt(((Integer) ???.next()).intValue());


Not sure what I need to put in for the ??? either, since I assume I do not need to create a new tree here. But in my code I use the following code to create my tree...

public class BinaryTree implements Serializable {

private Node root;

private static class Node {

Node left;

Node right;

int data;

Node(int newData) {

left = null;

right = null;

data = newData;



// Creates an empty binary tree -- a null root pointer.

public void BinaryTree() {

root = null;


Open in new window

Question by:concertandy
    LVL 92

    Expert Comment

    Why doesn't the builtin serialization method work?


    Author Comment

    The built in one does work, we just have to improve the performance of the builted in version of writeObject().


    Accepted Solution

    If I add the following next(), and hasNext() methods would my code in the next code tagged writeObject?
    // node of the last value returned by next() if that
    // value was deleted by the iterator method remove()
    private Node lastReturned = null;
    // node whose value is returned a subsequent call to next()
    private Node nextNode = null;
    // returns true if the tree has more
    // unvisited elements
    public boolean hasNext() {
    // elements remain if nextNode is not null
    return nextNode != null;
    public T next() {
    // check that the iterator is in a consistent state.
    // throws ConcurrentModificationException if it
    // it is not
    // check if the iteration has an another element
    // if not, throw NoSuchElementException
    if (nextNode == null)
    throw new NoSuchElementException("Iteration has no more elements");
    // save current value of next in lastReturned.
    lastReturned = nextNode;
    // set nextNode to the next node in order
    Node p;
    if (nextNode.right != null) {
    // successor is the furthest left node of right subtree
    nextNode = nextNode.right;
    while (nextNode.left != null)
    nextNode = nextNode.left;
    else {
    // have already processed the left subtree, and
    // there is no right subtree. move up the tree,
    // looking for a parent for which nextNode is a left child,
    // stopping if the parent becomes null. a non-null parent
    // is the successor. if parent is null, the original node
    // was the last node inorder
    p = nextNode.parent;
    while (p != null && nextNode == p.right) {
    nextNode = p;
    p = p.parent;
    // if we were previously at the right-most node in
    // the tree, nextNode = null
    nextNode = p;
    private void writeObject(ObjectOutputStream s) throws IOException 
    { System.out.println("call specialized writer");
    // Write out treeSize and internal serialization magic
    for (Iterator i = iterator(); i.hasNext(); )

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
    INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
    Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    11 Experts available now in Live!

    Get 1:1 Help Now