3D-kreativ
3D-kreativ

Reputation: 9309

Guidelines about saving objects to file

I'm working with a hand in task that is like a simple bank with customers and different accounts. Now I have to develop my task to store my customer objects and account object to file. I have read some about it and I'm going to use the ObjectOutputStream and the ObjectInputStream.

Since I have all customer objects in an arraylist, called customerList and all account objects that belongs to the customers in an arraylist, called accountsList, I wonder if I should and can save the hole arraylist or should I save all objects separately?

And when I'm going to load the customer object, should I put them in an arraylist again to be able to access them as I have done until know? Looking for a good and simple to understand solution. Preciate the help! Thanks!

Perhaps I can just make a loop and pick each object in the array list and save them as object. And then when I'm going to load them just make a loop again and load them and add them to array list!?

Upvotes: 0

Views: 81

Answers (2)

Aravind Yarram
Aravind Yarram

Reputation: 80194

You can save (technical term is serialize) any object as long as they implement java.io.Serializable. ArrayList implements Serializable so as long as your Customer and Account objects implement are also implementing Serializable interface there will be no problem.

Example of serialization with ArrayList: http://www.javabeginner.com/uncategorized/java-serialization

NOTE: The better way to store long term (and production) data is to use a DBMS (RDBMS or NoSQL DB) system.

Upvotes: 1

Joni
Joni

Reputation: 111339

It's easier to store and load the entire arraylist than individual objects. Either way you need to make sure your objects are serializable.

In a non-homework setting you would probably have the list of accounts stored in a separate object that includes all of the persistsnt application state. Then in startup you would read the state, and store it on shutdown. You should make sure your classes define a serial version uid so that if you change their structure you can mark the new version incompatible with old data.

Finally, banking data should be stored in a reliable database. The serialisation mechanism is meant for short-term storage, like in communication protocols, or for relatively unimportant data like browser history or user preferences. Using it for long term storage means that you can't modify the classes you used or you risk losing data.

Upvotes: 1

Related Questions