Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best Serializable replacement for "Set" and "Collection" interfaces?

Tags:

java

I have to serialize Collection and Set interfaces. Which are the best Serializable replacements for those interfaces on Java?

like image 317
Light Harut Avatar asked Jan 20 '12 11:01

Light Harut


People also ask

Which methods of Serializable interface should I implement?

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.

What is serialization alternative in Java?

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.

Which interface is used for serialization?

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.

How can we serialize an object without using Serializable interface in Java?

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.


2 Answers

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.

like image 158
Farmor Avatar answered Oct 15 '22 19:10

Farmor


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.

like image 2
Kushan Avatar answered Oct 15 '22 19:10

Kushan