Type inference for generic container in Java
Written by P. Most   

How can you instantiate generic containers without the need to repeat the type parameters in the constructor call?

Since Java 5 you can and should use the generic and type safe containers like List<>, Map<> etc. But probably everybody who has used them finds is quite annoying that it is necessary to repeat the generic type parameters when calling the constructor i.e.:

Map< String, List< String >> map = new HashMap< String, List< String >>();

Java 7 will address this issue with the introduction of the diamond operator which makes it possible to write:

Map< String, List< String >> map = new HashMap<>();

A pre-jdk7 compiler is not able to deduce the type parameter, but it is able to do that with methods. So with the aid of a little generic factory method, you can get almost the same effect:

public abstract class HashMapFactory
{
    public static < K, V >
        HashMap< K, V > newHashMap()
        {
            return new HashMap< K, V >();
        }
}

or for an ArrayList<>

public abstract class ArrayListFactory
{
    public static < T >
        ArrayList< T > newArrayList()
        {
            return new ArrayList< T >();
        }

    public static < T >
        ArrayList< T > newArrayList( int size )
        {
            return new ArrayList< T >( size );
        }
}

and with a static import you don't even have to write the factory class name:

import static  HashMapFactory.*


Map< String, List< String >> map = newHashMap();

This of course begs the question why is the diamond operator introduced when you basically can have the same effect with a library solution? It is also, as Filip Frącz has noted, a little short sighted, because why not introduce real type inference like C++, C# and Scala have, then this would have been much more powerful.


BTW: This is not a new technique. C++ has done this for years for example with make_pair.

Last Updated on Tuesday, 01 February 2011 12:00
 
PERA Software Solutions GmbH, Powered by Joomla! and designed by SiteGround web hosting