class pair<U,V>{
U first;
V second;
public pair() {
first = new U(); //error
second = new V(); //error
}
public pair(U f,V s){
first = f;
second = s;
}
}
required: class
found: type parameter
Is it possible to initialize first/second with (without-arguments) constructor of U/V type other way?
Java does not normally allow this because of type erasure. You can specify constructor arguments of type
Class<U>andClass<V>, for which you would pass in concrete class types of the given type parameters (i.e.,Integer.classandString.classfor<Integer>and<String>).It is also possible to extract the type using bytecode-level reflection, but quite complicated, and it doesn’t always work in all situations. If you scroll down on this article, you can find the example that makes this possible. I’ve pasted it below for convenience.
Edit: for reply to comment: