Reputation: 4637
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?
Upvotes: 3
Views: 65
Reputation: 20254
The method call works because you haven't constrained the type T
and since both String
and Integer
are sub-types of java.lang.Object
that is that type that will be inferred.
Upvotes: 2
Reputation: 4305
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.
Upvotes: 2
Reputation: 48404
Your method will compile and not throw any exception at runtime.
The reasons are:
T extends CharSequence
, etc.), any Object
and "boxable" primitive will compile as parameter during invocationequals
on the parameters is tantamount to invoking Object#equals
in this case, hence no runtime exception will be thrown. false
will be returned as the references between your arguments are not equalIf you invoke your method with objects sharing the same reference, it will print true
.
If you invoke your method with objects sharing the same value (e.g. two equal String
s), it will return true
.
Upvotes: 0