| 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.: Java 7 will address this issue with the introduction of the diamond operator which makes it possible to write: 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: or for an ArrayList<> and with a static import you don't even have to write the factory class name: 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 |