Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 278
CodingKobold Avatar asked Dec 18 '12 21:12

CodingKobold


People also ask

Why do we use generics for getting a list of multiple elements?

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.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.

When using Java generics You can specify multiple 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.


1 Answers

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.

like image 123
NPE Avatar answered Sep 23 '22 19:09

NPE