对于其类实现Serializable的对象的notserializableexception

vis*_*050 -1 java serialization

我有这门课

public class wordObject implements java.io.Serializable
    {
        String wordName;
        int occCount;
        int count;
        HashMap<Integer, Double> lineDict;
        int[] mat;

        public wordObject(String name,int num)
        {
            wordName = name;
            occCount=1;
            count = num;
            lineDict=new HashMap<Integer,Double>(lineC);
            mat = new int[lineC];

        }

    }
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用下面给出的一段代码将类的实例写入磁盘时

public static writeObj(WordObject obj)
    FileOutputStream f_out = new FileOutputStream(loc);

            // Write object with ObjectOutputStream
            ObjectOutputStream obj_out = new ObjectOutputStream (f_out);

            // Write object out to disk,obj is instance of wordObject
            obj_out.writeObject ( obj );
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

Exception in thread "main" java.io.NotSerializableException: searchTAemd
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

我们非常欢迎任何帮助.

编辑:我已经检查过HashMap已经实现了serializable.

Joa*_*son 6

由于wordObject是内部类,并且内部类始终保持对其外部类的隐式引用,因此除非外部类也可序列化,否则不能序列化内部类.实际上甚至不建议尝试;

序列化规范 ;

由于多种原因,强烈建议不要对内部类(即非静态成员类的嵌套类)进行序列化,包括本地类和匿名类.因为在非静态上下文中声明的内部类包含对封闭类实例的隐式非瞬态引用,所以序列化这样的内部类实例也将导致其关联的外部类实例的序列化.