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?
Tis inferred to beObject, and both arguments are getting implicitly upcast.Thus the code is equivalent to:
What may be even more surprising is that the following compiles:
The second argument is getting auto-boxed into an
Integer, and then both arguments are getting upcast toObject.