Saturday, July 17, 2010

Creating objects of generic types

In this post I will cover an issue that is solved in JDK 7.0, but most of us who work with generics still use JDK 5.0 and JDK 6.0.
If we want to create an instance of HashMap we would need to specify the generic types both at the varible definition and after the "new" keyword.
For example:


This isn't too bad, but what happens when we need to create a HashMap like this:


Suddenly, this gets too annoying.
JDK 7.0 suggests the following solution:


But as previously mentioned, most of us don't use this version of JDK.

Google came with a nice solution in their google collections framework based on static generic methods.
If we look at their Maps utilities class we can notice the newHashMap method, which provides us the following usage:




Genrics are an important feature when we want to have code reuse in our software - this means that in many situations we (or others) may use generics we coded in many locations in our software, and this led me to think - why shouldn't we as a rule provide a static "newMyGeneric" method to generics we code?

For example:



And a possible usage would be:


It clearly can be seen that multiMap2 is initialized in a more elegant way.

To conclude this post, I want to remind once again that JDK 7.0 is solving the presented problem. However, the suggested solution can help for current projects, and of course, if a development team upgrades its JDK to JDK 7.0, the suggested solution will still work, although it may be somewhat obsolete.

No comments:

Post a Comment