0

I have this class:

public class Bank  implements Serializable{
    ArrayList<Person> people;
    HashMap<Integer, Set<Account>> bank;

    ...
}

How do I serialize/deserialize an object of instance Bank? I found lots of examples on the internet on how to serialize/deserialize a list or a hashMap, but I didn't find an example for serialize/deserialize both or something more complex. How should I do this? Any advice is welcome. Thanks!

SomeoneNew
  • 91
  • 9
  • 1
    Just ensure Person and Account are serializable basically – Michael May 03 '17 at 09:59
  • both ArrayList and HashMap are serializable, what the issue here ? show us what you have tried so far. – Amit May 03 '17 at 09:59
  • @AmitK Set may or may not be (all of the Collections set implementations are but the interface doesn't make the guarantee). And his custom classes may not be either. – Michael May 03 '17 at 10:01
  • @Michael , OP is not using set and his custom class are nothing but the the instance of AL and Map and both are serializable. – Amit May 03 '17 at 10:02
  • 1
    oops sorry missed that.. – Amit May 03 '17 at 10:03

1 Answers1

1

In order for a class to be serializable, either:

1) Each type which it encapsulates must also be serializable

or

2) That field must be marked as transient (which means they are not serialized)


Let's look at the types your Bank class is using:

The first three are all serializable (as we can see from their JavaDocs) so there's no problem there.

Set is not by definition serializable but all of the implementations in java.util are so you're probably safe. However, if you're relying on the set being serializable you should probably change your definition so it's more explicit:

HashMap<Integer, HashSet<Account>> bank;

Person and Account are classes which I assume you've written yourself. You haven't provided them but make sure that they also implement serializable. If they aren't also serializable, I believe your ArrayList will throw an exception if you try to serialize it.


Additionally, make sure your serializable classes contain a serialVersionUID. What is a serialVersionUID and why should I use it?

Community
  • 1
  • 1
Michael
  • 41,989
  • 11
  • 82
  • 128