java - HashMap not Serializable -


hashmap serializable key/value supposed serializable.

but it's not working me. tried other io streams. none works.

any suggestion?

test code

public class simpleserializationtest {     @test     public void testhashmap() throws exception {         hashmap<string, string> hmap = new hashmap<string, string>() {{             put(new string("key"), new string("value"));         }};          bytearrayoutputstream bos = new bytearrayoutputstream();         objectoutput out = null;         out = new objectoutputstream(bos);         out.writeobject(hmap);         byte[] yourbytes = bos.tobytearray();         if (out != null) {             out.close();         }         bos.close();          bytearrayinputstream bis = new bytearrayinputstream(yourbytes);         objectinput in = null;         in = new objectinputstream(bis);         object o = in.readobject();         bis.close();         if (in != null) {             in.close();         }          assertequals(hmap, o);     } } 

stack trace

java.io.notserializableexception: simpleserializationtest     @ java.io.objectoutputstream.writeobject0(objectoutputstream.java:1184)     @ java.io.objectoutputstream.defaultwritefields(objectoutputstream.java:1548)     @ java.io.objectoutputstream.writeserialdata(objectoutputstream.java:1509)     @ java.io.objectoutputstream.writeordinaryobject(objectoutputstream.java:1432)     @ java.io.objectoutputstream.writeobject0(objectoutputstream.java:1178)     @ java.io.objectoutputstream.writeobject(objectoutputstream.java:348)     @ simpleserializationtest.testhashmap(simpleserializationtest.java:18)  process finished exit code 0 

the exception message tells problem is: trying serialize instance of class simpleserializationtest, , class not serializable.

why? well, have created anonymous inner class of simpleserializationtest, 1 extends hashmap, , trying serialize instance of class. inner classes have references relevant instance of outer class, , default, serialization try traverse those.

i observe use double-brace {{ ... }} syntax if think has sort of special significance. important understand 2 separate constructs. outer pair of braces appearing after constructor invocation mark boundaries of inner class definition. inner pair bound instance initializer block, such can use in any class body (though unusual in contexts other anonymous inner classes). ordinarily, include 1 or more method implementations / overrides inside outer pair, either before or after initializer block.

try instead:

    public void testhashmap() throws exception {         hashmap<string, string> hmap = new hashmap<string, string>();          hmap.put(new string("key"), new string("value"));          // ...     } 

Comments