Is it possible to serialize a general purpose collection?

If I have a collection Collection<SomeClass> classes;, can it be serialized as is? Or do I need to declare it as an ArrayList, HashSet, or some other specific implementation that implements Serializable? If so, what is the common practice for this?

+4
source share
2 answers

As long as it SomeClassis serializable, any standard java.util.collectionobjects SomeClasswill be serializable.

I always assumed that this is due to the fact that the interface itself Collectionhas expanded Serializable, but, as you noted in your comment, this is not so. So, I performed the following test:

public class Test {
    static final String filename = "d:/desktop/employee.txt";
    Collection makeColl(){
       return new ArrayList();
    }

    void writeColl(Collection c){ 
        try {
              ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("d:/desktop/employee.txt"));
              out.writeObject(c);
              out.close();
          } catch(IOException i){i.printStackTrace();}
    }

    Collection readColl(){
        Object that = null;
        try {
           ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
          that = in.readObject();
        } catch(IOException | ClassNotFoundException i) { i.printStackTrace(); }
        return that;
    }

public static void main(String[] args) {
    Test t = new Test();
    t.writeColl(t.makeColl());
    System.out.println(t.readColl().getClass()); 

  }

and what is printed: "class java.util.ArrayList"

So, what we can learn from this is that, although the interface Collectiondoes not directly apply to Serializable(and does not even matter List, Setor other sub-interfaces), all standard implementations of these interfaces. In addition, when you make a serialization call on an object that implements Collection, it will be serialized as an object of its specific class (in the case of the above test ArrayList). This, of course, always takes place when you serialize an object known only to the interface for the serialization method.

, ( ): , , a Collection , , , Serializable ( ) . , , , Java .

: , Collection (, , ), NotSerializableException , Collection , Serializable, .

+1

Collection JDK Serializable: , Collection Serializable, (, ArrayList, HashSet ..) Serializable.

( ) , Serializable Collection, , (SomeClass ) Serializable t .

+2

Source: https://habr.com/ru/post/1542589/


All Articles