I have to serialize Collection and Set interfaces. Which are the best Serializable replacements for those interfaces on Java?
The Serializable interface must be implemented by the class whose object needs to be persisted. The String class and all the wrapper classes implement the java. io. Serializable interface by default.
Some examples of these formats are JSON, Protocol Buffers (Protobuf), and Avro. While Protocol Buffers and Avro also can facilitate schema verification as well as have extensions for remote procedure call systems (RPC) they are still much simpler than Java serialization is when it comes to simply transfering state.
Serializability of a class is enabled by the class implementing the java. io. Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized.
As per the Java Object Serialization Specification, we can use the writeObject() method from ObjectOutputStream class to serialize the object. On the other hand, we can use the readObject() method, which belongs to the ObjectInputStream class, to perform the deserialization.
Set is an Interface.
Use HashSet that are implementing Set and HashSets are serializable.
Just be sure that all the objects in the Set is serializable.
For more info Why java.util.Set is not Serializable?
PS. It doesn't have to be a HashSet; use any concrete class that is serializable and implementing Set or Collection.
The type checking knows that set is not serializable, but a subtype of set can be serializable.
Set is a Interface. But implementation of set is HashSet. This is serializable.
You would not expect to serialize a Set because a Set can not be instantiated.
Set st = new Set(); // illegal
So set doesn't really need to implement Serializable.
Anyway, you can use LinkedHashSet and TreeSet. Those are also Serializable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With