So the point of the other thread (java compiler) was I could not test any solutions I came up with at home for my next question.

My assignment 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");
    s.writeInt(_v.size());
    for (Iterator i = _v.iterator(); i.hasNext(); )
      s.writeInt(((Integer) i.next()).intValue());
  }

  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++)
      addBack(in.readInt());
  }

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"));
os.writeObject(L);
os.flush();

ObjectInputStream in
  = new ObjectInputStream
    (new FileInputStream("out.dat")); 
IntListSerializable V = (IntListSerializable) in.readObject();

---------------------------------------------------------------------------------

My ReadObject Method is ...

   private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
  { System.out.println("call specialized reader");
     BinaryTree read = new BinaryTree();
     int size = in.readInt();
     for (int i = 0;  i<size; i++)
        read.insert(in.readInt());  //my insert method.
  }

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?

   Prints the node values in the "inorder" order.
   Uses a recursive helper to do the traversal.
   */
       public void printTree() {
         printTree(root);
         System.out.println();
      }

       private void printTree(Node node) {
         if (node == null) 
            return;

      // left, node itself, right
         printTree(node.left);
         System.out.print(node.data + "  ");
         printTree(node.right);
      } 

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;
      }

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();

or

Node X = (Node)in.readObject();

Recommended Answers

All 8 Replies

I see a lot of views, but may be I am not asking the question right.

I need to write my writeObject method so when read in by the testing file it will produce an output file, but I am unsure how to do this using a tree. An array, and linked list no problem, but the tree seems to have me stumped.

some advice if adding these two methods will work..

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
checkIteratorState();

// 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;
}

lastReturned.nodeValue;
}
private void writeObject(ObjectOutputStream s) throws IOException 
{ System.out.println("call specialized writer");
// Write out treeSize and internal serialization magic
s.defaultWriteObject();
for (Iterator i = iterator(); i.hasNext(); )
s.writeInt(((Integer) i.next()).intValue());
}

defaultWriteObject is equivalent to the default serialization performed in the absence of a writeObject method and is normally used in conjunction with custom writes to persist transient or extra data. Hence you might want to resort to something else.

One solution might be to grab the contents of the entire binary tree in a List, serialize that list using ObjectOutputStream.writeObject in the writeObject method, read the same and populate your tree.

Here I am assuming that the elements inserted in the BinaryTree have natural ordering i.e. implement the Comparable interface.

> I see a lot of views, but may be I am not asking the question right.

Consider using code tags and proper indentation when posting code.

Ok, I got it to wrok, sort of.

I need to use the "package serialization;" and to "implement Serializable" but once I add this to my file it give me the following message,

java.lang.NoclassDefFoundError BinaryTree <wrong name:serialization/BinaryTree?

I tried adding the exception, and importing the exception and still get error message.

I think it may have something to do with javac 1.6 which I just dowloaded.

PS. I got the file to right with that method, but with out the serialization package working I cant really see if the file size is different and we have improved performance.

> java.lang.NoclassDefFoundError

You need to show us the command line invocation of `java' which you are using to run your program. If your class 'Z' is inside a package 'my.pkg' inside the directory 'test', you need to use a command like:

c:\test>java my.pkg.Z

Read the links specified in the forum sticky for a detailed explanation.

>I got the file to right with that method, but with out the serialization
>package working I cant really see if the file size is different and we
>have improved performance.

Huh? Improved performance?

I am not sure what you mean by "inside a package".

I have two jave files within one folder and the only difference is one has a 1 at the end of it (BinaryTree, and BinaryTree1).

There is two classes in my file
Binary Tree
Node

Then at the bottom I have a main which provides out put from my binary tree. In order and postorder printout and then the writing of my file (out.day).

Which link would give a detailed explanation. I do not mind going through the documentation.

As for the improved performance, our assignment is to see how serialization shrinks a file when you use a better performing writeObject/readObject. One file has size say 10K, and the other 5K. Showing improved performance.

I figured out what was wrong. I forgot to add "Implements Serializable" to one of my sub classes on my code. 'doh that is why I was getting the above error.

> Which link would give a detailed explanation.

For future references, almost all the links in this thread are pretty good for someone starting out with Java; worth a look.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.