Type Inference
One noteworthy JDK 7 feature is that you needn’t specify the value of the type parameter explicitly as you must when invoking generic constructors. The compiler figures out the value of the type parameters by examining the types of the constructor arguments. This process is called type inference. For example, consider the following generic class and its instances :
Notice how gen1 is declared. The type arguments (which are Integer and String) are specified twice: first, when gen1 is declared, and second, when a Gen instance is created via new. Since generics were introduced by JDK 5, this is the form required by all versions of Java prior to JDK 7. Although there is nothing wrong, per se, with this form, it is a bit more verbose than it needs to be. In the new clause, the type of the type arguments can be readily inferred from the type of gen1; therefore, there is really no reason that they need to be specified a second time. To address this situation, JDK 7 added a syntactic element that lets you avoid the second specification. Today this declaration can be rewritten.
Notice how gen2 is declared, that the instance creation portion simply uses <>, which is an empty type argument list. This is referred to as the diamond operator. It tells the compiler to infer the type arguments needed by the constructor in the new expression. The principal advantage of this type-inference syntax is that it shortens what are sometimes quite long declaration statements.
Program
class Gen<T, U> { private T t; private U u; Gen(T tt, U uu) { t = tt; u = uu; } T getT() { return t; } U getU() { return u; } } public class Javaapp { public static void main(String[] args) { Gen<Integer, String> gen1 = new Gen<Integer, String>(40, "Fifty"); Gen<String, String> gen2 = new Gen<String, String>("Thirty", "Fifty"); System.out.println(new Gen<>(50, 100).getU()); } }