2

I believe I can provide explicit type arguments for the class while invoking constructor with new operator, like this:

MyClass<?> obj = new MyClass<Float>("test", 1);

where MyClass is defined like this:

class MyClass<T>{
    <K, V> MyClass(K k, V v){        
}

I suppose in this case Float is assigned to type parameter T. And for K & V compiler infers the type from actual arguments provided.

My doubt is how I can provide explicit type arguments for constructor? I know for methods I can do like obj.method<Integer, String>(1, "test");

I wonder is this kind of explicit type arguments(for K&V; not for T) are possible with constructors.

Hoping somebody can clear this for me. Thanks in advance.

2
  • Uhm, if your class accepts type parameters, they should all be declared in the class declaration. Why define only one if you need two anyway? Commented Mar 25, 2015 at 10:24
  • @fge: These are not the class's type parameters, but type parameters for the generic constructor (similar to type parameters for a generic method). Commented Mar 25, 2015 at 20:01

1 Answer 1

7

You give type arguments between new and class name:

MyClass<?> obj = new <String, Integer>MyClass<Float>("test", 1);

BTW, for methods you give type argument before method name:

obj.<Integer, String>method(1, "test");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.