Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
Paul Tomblin Avatar asked Mar 25 '10 13:03

Paul Tomblin


3 Answers

Wrap strings in wrapper-classes if you want:

class GroupId implements Comparable {
   private String groupId;

   public GroupId (String groupId) {
       this.groupId = groupId;
   }
   ...
}

Map<GroupId, List<CapabilityId>> m = ...
like image 165
Roman Avatar answered Sep 30 '22 04:09

Roman


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.

like image 29
Jim Kiley Avatar answered Sep 30 '22 04:09

Jim Kiley


Create an ID class which you can subclass, and which consists of a String field and implementations of equals() and hashCode() which use that field.

like image 20
Michael Borgwardt Avatar answered Sep 30 '22 06:09

Michael Borgwardt