· 1 min read

Easier Java Generics object construction

I’ve been programming with JDK 5.0 for a bit now and just love the generics features. However, I find that I keep repeating myself when constructing collection instances.

For example:

<br /> Map<String, Collection<File>> files = <br /> &nbsp;&nbsp;new HashMap<String, Collection<File>>();<br />

I recently discovered in this blog posting that a simple static method would allow:

<br /> Map<String, Collection<File>> files = Util.newMap();<br />

The code for the utility (excerpted from the blog entry referenced above) looks like this:

<br /> public static <K,V> Map<K,V> newMap() <br /> {<br /> &nbsp;&nbsp;return new HashMap<K,V>();<br /> }<br />

Clearly, saves a bunch of typing and is easy to implement. The author of the posting mentioned he’s added it as an RFE as well.

    Share:
    Back to Blog