0

I am trying to serialize a Trie in Java (prefix tree), so I wrote this code

public void serialize(DictNode node, ObjectOutputStream outPut){
    if (node == null) {
        return;
    }
    int i;
    if(node==root){
        try{    
            System.out.println(node+"   root");
            outPut.writeObject(node);
        }catch(IOException ex) {
            ex.printStackTrace();
        }
    }

    for(i=0;i<26;i++){
        if(node.array[i]!=null){
            System.out.println(node.array[i]+"   ser  "+(char)(i+'a'));
            try{    

                outPut.writeObject(node.array[i]);
            }catch(IOException ex) {
                ex.printStackTrace();
            }
            serialize(node.array[i],outPut/*,temp*/);
        }

    }
}

But it doesn't seem to work properly. So here is the thing. When I wrote a System.out.println in order to print the adresses of the nodes that I pass througth in the code that I wrote to priint the leafs. But when I do the same thing in the method of serialization the adresses are completely different even thought the code is the same. Why does this happen????

public void printLeafNodes(DictNode node,String preflix) {
    if (node == null) {
        return;
    }
    int i;
    if(node.isTerminalNode){
        System.out.println(preflix);
    }

    for(i=0;i<26;i++){
        if(node.array[i]!=null){
            System.out.println(node.array[i]+"    "+(char)(i+'a'));
            Character.toString((char)(i+'a'));
            preflix=preflix+(char)(i+'a');
            printLeafNodes(node.array[i],preflix);
            preflix=preflix.substring(0,preflix.length()-1);
        }

    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161

1 Answers1

0

You print the adress of an Object (DictNode) which is different every time you serialize/desirialize, because java has to create new instances.

If you would add a toString() Method to class DictNode you will see that the content of the class is what you expect to see.

In toString() you can create a String which contains all class field informations like "name=Hans,lastname=Wurst,age=12"

Check:

Community
  • 1
  • 1
Markus Lausberg
  • 12,177
  • 6
  • 40
  • 66
  • So you are telling me that it doesn't matter the adresses are different as soon as the class field information are correct – Dimitris Manonegra Mar 14 '17 at 11:52
  • Yes, the adress is a link to the memory, but this is changning when creating new instances. Important is the content of the object. You write the adress, but you want to see a description of the class, which can be solved by implementing toString() – Markus Lausberg Mar 14 '17 at 12:28
  • Thank you. Your advice was very helpfull – Dimitris Manonegra Mar 14 '17 at 12:54