Reputation: 71
sorry, this question might be very simple but I didn't find the answer in the internet.
public class Main {
public static void main(String[] args) {
int a = 1;
double b=2;
max(a,b);
}
public static <E> void max(E first , E second)
{
System.out.println(first);
System.out.println(second);
}}
when we pas the first parameter an integer then E is set to Integer and then we pass a double to it. we should get a compile error. (because E is Integer) but the program runs correctly and the output is
1
2.0
so what is my mistake?
Upvotes: 3
Views: 73
Reputation: 575
Based on my understanding, there are two things. one is generic class and other one is generic method. In both the cases, you can pass any type of value (regardless of type) you can pass any type of parameter. Now when you are creating an object of specific generic lass type like MyClass<Integer>
its no more generic, you can expect compiler error while doing operation with different type of parameter. But when you have some method like which adds element to a List<E>
, you can add anything to this list, you will not get any compilation error.
Upvotes: 0
Reputation: 394136
If you hover over the method call in Eclipse, you'll see:
<? extends Number> void Main.max(? extends Number first, ? extends Number second)
i.e. the compiler infers the type of the generic type parameter as something that extends Number
. Therefore, both Integer
and Double
, which extend Number
are valid arguments for the max
method.
If you print the types of the arguments passed to the max
method:
public static <E> void max(E first , E second)
{
System.out.println(first);
System.out.println(second);
System.out.println (first.getClass ());
System.out.println (second.getClass ());
}
you'll see that an Integer
and a Double
were passed to the method:
1
2.0
class java.lang.Integer
class java.lang.Double
Upvotes: 4
Reputation: 43600
Java's type inference algorithm finds the most specific type that your arguments share. In this case, it should be Number.
Upvotes: 3