views:

45

answers:

1

I am serializing an ArrayList in 2 classes:

private void serializeQuotes(){
        FileOutputStream fos;
        try {
            fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(quotesCopy); 
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    private void deserializeQuotes(){
        try{
            FileInputStream fis = openFileInput(Constants.FILENAME);
            ObjectInputStream ois = new ObjectInputStream(fis);
            quotesCopy = (ArrayList<Quote>) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
    }

Let's assume:

1. Class A serializes Quotes
2. Class B deserializes Quotes
3. Class B adds stuff to Quotes
4. Class B serializes Quotes

Can I safely assume Quotes will be updated and is in sync between the two classes?

+2  A: 

From what you've described, no.

Serializing an object basically just writes a snapshot of it to a stream so that it can be saved to disk or transferred elsewhere and read. There is no syncing of data involved. Changing an object you've deserialized will have no effect on the object it was originally serialized from... there's no link whatsoever. Simply serializing the object to a shared file won't cause any kind of syncing either, since nothing that is using the file is going to automatically read the file and synchronize its state when the file is written to without you adding code to approximate that effect yourself.

ColinD
That doesn't apply to what he's doing. He is serializing, deserialing, changing the deserialized object, and re-serializating it. Provided the operations don't overlap, it should work 100%.
EJP
@EJP What do you mean by "should work"? If he added a 5th step where Class A deserialized the quotes from the file, then they should have the same quotes after that series of steps. But he doesn't, so Class A and B will not have the same quotes.
ColinD