Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method works with different actual parameter

Tags:

java

generics

Here I have a generic method which accepts a generic type parameter T

 public static <T> boolean compare(T p1, T p2) {
        return p1.equals(p2);
    }

now if I call this method like below

compare(10, "");

it works but as I assume it shouldn't work cause it can accept only one type of Type parameter, so how inference algorithm works here?

like image 337
eatSleepCode Avatar asked Sep 13 '26 22:09

eatSleepCode


1 Answers

It works because Integer and String have common parent: Object and you do not specify any constraint in type T. If you write:

public static <T extends Number> boolean compare(T p1, T p2) {
    return p1.equals(p2);
}

you get compile time error.

like image 105
sibnick Avatar answered Sep 16 '26 10:09

sibnick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!