Re: HashMap toString, what about the other way?
Lew wrote:
Bas wrote:
Hi,
is there a way to reconstruct a HashMap from the output of toString?
E.g.
HashMap m = new HashMap();
// put some stuff in it
String s = m.toString();
This is already pathological.
// s contains something like {blah=123, lalanana=hutsefluts}
HashMap c = (HashMap)somethingThatICantFind(s);
Or I'm a hoping for something that just doesn't work that way? ;)
You could hack (or read the source code for) the HashMap String
representation and develop a parse algorithm, but it's possible that the
HashMap toString() implementation could change between JVMs or between
JVM versions. Unlikely, but possible.
It is not necessary to read the code, just the API documentation.
HashMap inherits toString from AbstractMap, and AbstractMap's
documentation says exactly what it produces.
It would work if, and only if, there is enough additional data to
recreate each key and value from its toString. For example, "42" is the
toString result for both "42" and new Integer(42). For many classes the
toString result is clearly insufficient to recreate the object.
String seems like an incredibly bad choice for object serialization.
Especially since HashMap is Serializable.
Patricia