Java – what is the purpose of calling type parameters in the new constructor?
In Java specification( http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls -In 15.9), new has the following form:
ClassInstanceCreationExpression ::= | new TypeArguments_opt TypeDeclSpecifier TypeArgumentsOrDiamond_opt ( ArgumentListopt ) ClassBodyopt | Primary . new TypeArguments_opt Identifier TypeArgumentsOrDiamond_opt ( ArgumentListopt ) ClassBodyopt
What is the purpose of the new first optional type parameter list? I can't read section 15.9 (all references to the type parameter list seem to refer to the list after the type / Identifier) Testing random bits on the standard Java compiler can produce confusing results:
public class Foo<T> { } // ... Foo<Integer> t1 = new <Integer> Foo<Integer>(); // works Foo<Integer> t2 = new <Integer> Foo(); // works -- unchecked warning missing the type arg after Foo Foo<Integer> t3 = new <Boolean> Foo<Integer>(); // works Foo<Integer> t4 = new <Float,Boolean> Foo<Integer>(); // works Foo<Integer> t5 = new <NotDefined> Foo<Integer>(); // fails -- NotDefined is undefined
In these simple examples, it seems that this first parameter list has no meaning, although it parses and checks the validity of its parameters
Solution
Constructors can also declare type parameters
public class Main { public static class Foo<T> { public <E> Foo(T object,E object2) { } } public static void main(String[] args) throws Exception { Foo<Integer> foo = new <String> Foo<Integer>(1,"hello"); } }
This is what < string > is for before the constructor call It is the type parameter of the constructor
following
Foo<Integer> foo = new <String> Foo<Integer>(1,new Object());
failed
In your last
Foo<Integer> t5 = new <NotDefined> Foo<Integer>(); // fails -- NotDefined is undefined
Notdefined is not a type found during compilation If so, it will only give you a warning that it is not used