November 19, 2014

A Judicious Use of Generics to Simplify Working With Java Maps.

I've always been a little ambivalent about Generics in Java but every now and then I come across a neat usage that really helps out.

In this case the neat usage is with Java Maps.

Java Maps Generics have always struck me as being a little all or nothing you can use generics to define the types of all the keys and all the values but it's a bit blunt instrument there is no way to individually relate the key to the type of the value.

To that end I've created a little open source code that certainly works for me in many use cases: TypedMap on GitHub. I'll get round to releasing a Maven-ised version of this on a public repo soon, but the code is pretty trivial.

It introduces an interface called a TypedKey that takes a generic type parameter that indicates the type of the value related to the key. This interface has no methods and can be implemented by any of your classes so that they can be used as keys.

It then introduces an interface called TypedMap which extends the core java.util.Map interface to add three new methods, putTyped, getTyped and removeTyped. These are generically typed variants on the java.util.Map put, get and remove methods taking a TypedKey to define the type of the value being worked with.

Taking advantage of the way Generics works, these interfaces provide compile time type safety and eliminate the need for casting values retrieved from the map as long as an appropriate TypedKey is used.

Two concrete implementations of the interfaces are provided: DefaultTypedKey and TypedMapDecorator.

The DefaultTypedKey is the simplest possible implementation of the TypedKey interface, it is a direct child of java.lang.Object and inherits the hashcode and equals semantics.

TypedMapDecorator delegates all java.util.Map functionality to an embedded Map instance and implements the typed methods backed by the embedded Map.

I'm still working on the generics usage to make it more elegant and to provide a greater degree of control to the user, but even in this version I believe that the use of a TypedMap with TypedKeys can significantly simplify code in many use cases.