HashMap
with Serializable
key/value is supposed to be Serializable
.
But it's not working for me. Tried some 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
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at SimpleSerializationTest.testHashMap(SimpleSerializationTest.java:18)
Process finished with exit code 0
new String("key")
, just write"key"
. A literal such as"key"
is already aString
object. You do not need to explicitly create a copy of thatString
object. – Upward