0

So for a programming exercise I have to save data into files. I used the interface Serializable to save my data.

The problem occurs when I deserialize my file. When I print my object deserialized I can see all the values that have been saved but when I add this object to an arraylist and try to display this object again, all my values are set to default (defined into my superclass).

I don't know if my question is clear but if you need more information please ask.

Here is a part of my code:

public static void loadData(Mouse mouse, Monkey monkey, String fileName) throws IOException, ClassNotFoundException, FileNotFoundException{

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));

    try{
        Animal animal = (Animal)ois.readObject();

    if (fileName == "Mice.ser"){
        animal = (Mouse)animal;
        mouse.setLists();
    }

    else{
        animal = (Monkey)animal;
        monkey.setLists();
    }
    }catch(Exception e){}
    ois.close();
}


public class Mouse extends Animal implements Serializable{
    protected List mouseG1 = new ArrayList();
    protected List mouseG2 = new ArrayList();

    public void setLists(){
    if (this instanceof MouseG1){
        mouseG1.add((MouseG1)this);
    }
    else{
        mouseG2.add((MouseG2)this);
    }
}

That's it, sorry for my english (and code) I'm a beginner (and french)

  • 1
    Could you add some code to the question? – Darshan Mehta Feb 15 '17 at 18:06
  • 1
    We need to actually see some code. Asking for debugging help without showing us the code is like asking a detective to solve a murder case without showing him the crime scene. – user2357112 Feb 15 '17 at 18:06
  • 1
    Sorry I add some code up there. – Thomas MAUCOURT Feb 15 '17 at 18:14
  • First, `if (fileName == "Mice.ser")` will not work; see http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java . Second, *never* write an empty `catch` block; at the very least, put `e.printStackTrace();` in there, so you know if something went wrong. Third, you almost certainly should not give each `Mouse` instance its own separate List(s). – VGR Feb 15 '17 at 18:30
  • @VGR I'll argue about empty catch block, sometimes it is useful to catch for example NumberFormatException instead of checking it with other methods – Dmytro Grynets Feb 15 '17 at 18:34
  • @DmytroGrynets There is never a good reason to leave it empty. If the exception is part of standard application behavior, log it at a low level, like [Level.FINE](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Level.html#FINE). – VGR Feb 15 '17 at 18:36
  • @VGR Hm, good point, never though about that this way, it is really reasonable, thank you – Dmytro Grynets Feb 15 '17 at 18:40
  • Finally I'm restarting the code to improve it and to simplify it. Maybe it will be easier to save after the modifications. Thank you anyway ! – Thomas MAUCOURT Feb 15 '17 at 21:07

0 Answers0