3

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?

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93

3 Answers3

2

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.

sibnick
  • 3,995
  • 20
  • 20
2

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.

codebox
  • 19,927
  • 9
  • 63
  • 81
0

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.

Mena
  • 47,782
  • 11
  • 87
  • 106
  • Thanks for the answer, I have a doubt what is the difference between ` extends Object>` and ``. – eatSleepCode Aug 17 '15 at 12:26
  • @eatSleepCode in this precise context, none technically, but one functionally. `?` is a wildcard for any type, while `T` is the definition of a type you can re-use, bounded or not by `extends...`. If you use `?`, you can't declare `T`s in your method argument list, body, or return type which will often limit your functionality. – Mena Aug 17 '15 at 12:32
  • Type erasure has nothing to do with it. If we had reified generics this would also work. – newacct Aug 18 '15 at 00:32
  • @newacct I haven't said type erasure is the cause of the behavior. It's a complementary piece of information here. – Mena Aug 18 '15 at 08:25
  • @Mena: It's not complementary. It's just completely irrelevant. – newacct Aug 18 '15 at 17:42