Why does this generic java method accept two objects of different type?

T is inferred to be Object, and both arguments are getting implicitly upcast.

Thus the code is equivalent to:

Main.<Object>random((Object)"string1", (Object)new Integer(10));

What may be even more surprising is that the following compiles:

random("string1", 10);

The second argument is getting auto-boxed into an Integer, and then both arguments are getting upcast to Object.

Leave a Comment