简体   繁体   中英

generics with different types

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?

If you hover over the method call in Eclipse, you'll see:

<? extends Number> void Main.max(? extends Number first, ? extends Number second)

ie 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

Java's type inference algorithm finds the most specific type that your arguments share. In this case, it should be Number .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM