eatSleepCode
eatSleepCode

Reputation: 4637

Generic method works with different actual parameter

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

Answers (3)

codebox
codebox

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

sibnick
sibnick

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

Mena
Mena

Reputation: 48404

Your method will compile and not throw any exception at runtime.

The reasons are:

  • Type erasure will prevent the JVM from knowing your parametrized type at runtime, and since you are not binding your parametrized type (e.g. T extends CharSequence, etc.), any Object and "boxable" primitive will compile as parameter during invocation
  • Invoking equals 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 equal

If 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 Strings), it will return true.

Upvotes: 0

Related Questions