This method shall take two objects of the same type and return one of those objects by random:
public static <T> T random(T o1, T o2)
{
return Math.random() < 0.5 ? o1 : o2;
}
Now, why does the compiler accept two parameters with distinctive types?
random("string1", new Integer(10)); // Compiles without errors
EDIT: Now that I know that both parameters are getting implicitly upcasted, I wonder why the compiler does complain when calling the following method:
public static <T> List<T> randomList(List<T> l1, List<T> l2) {
return Math.random() < 0.5 ? l1 : l2;
}
Call:
randomList(new ArrayList<String>(), new ArrayList<Integer>()); // Does not Compile
If those ArrayList Parameters are also getting upcasted to Object, why does it give me an error this time?
Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
A Generic class can have muliple type parameters.
Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With