Avoid custom objects as Map keys

how-to
May 20, 20091 min

Maps are the essential part of the Java Collections Framework. I loved to fill them with all kind of data and transport it between application layers. Until I stumbled upon the problem that I couldn’t fix. In Ajax world it’s just not possible to have custom object as keys. So once I tried to use the beautifully formed Map as a transport to the front-end via Ajax it resulted in a significant time lost on a workaround. First of all I needed to rethink the way data was transported and had to put it in an List of a newly introduced data structure. Then, I had to fix the way Struts 2 JSON Plugin dealt with Maps containing complex keys. It simply produces an invalid JSON string: https://code.google.com/p/jsonplugin/issues/detail?id=93&can=7 As a conscientious citizen I looked at the way DWR handled such Maps and copied its toString() approach to JSON Plugin. Lesson learned: beware of complex Map keys.