Search code examples
javacollectionstype-safety

Better type safety in Java collections


In my java coding, I often end up with several Map<String,Map<String,foo>> or Map<String,List<String>> and then I have trouble remembering which String is which key. I comment the declaration with //Map<capabiltyId,Map<groupId,foo>> or //Map<groupId,List<capabilityId>, but it's not the greatest solution. If String wasn't final, I would make new classes CapabilityId extends String and GroupId extends String, but I can't. Is there a better way to keep track of which thing is the key and maybe have the compiler enforce it?


Solution

  • Instead of having CapabilityId extend String, CapabilityId could include a String field called "id"; then your Map could be defined as Map<CapabilityId, Map<GroupId, Foo>>, and you could get at the individual ID fields through a getId() on your key classes.

    I'm not sure I would do this myself, but if I did, this is probably what I'd do.

    You could limit the clutter by having an abstract GenericId class with an id field and getId() method, and have CapabilityId and GroupId inherit from it.