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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With