0

I am learning Java generics and tried the below code

class A {

    public <T> void pick(T a, T b){
        System.out.println(b.getClass().getName());
        System.out.println(a.getClass().getName());
    }
}

    new A().pick("abc", 5);

Here my idea is that pick function's parameter should be of same type as both are T.

However when I am calling it using new A().pick("abc",5) there are no compile time error.

Rather I get the result b is Integer class and a is String class

Can any one help me with this concept.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
voila
  • 1,594
  • 2
  • 19
  • 38
  • There is no need for a compiler error as long as there is a type for `T` that is a common type of String and Integer. – Tom Dec 11 '22 at 08:48
  • 2
    In this case `T` is `Object`. – tgdavies Dec 11 '22 at 08:48
  • 1
    Similar question (for arrays, but that difference is not important): [Single generic parameter accepts two different types at the same time](//stackoverflow.com/q/14183170) – Tom Dec 11 '22 at 08:55
  • Thank you guys, I think I need to study more ..:) :) – voila Dec 11 '22 at 08:59
  • @Joe : Thank you, it was linked in the above comment as well. Yes its kind a explains but the below accepted answer is more precise – voila Dec 11 '22 at 09:12

1 Answers1

1

You didn't specify any bounds for your generic type. In this case, T will fall back to Object. You won't get any compiler errors as this is perfectly valid.

You probably want to do something like

class A {

    public <T extends SomeClass> void pick(T a, T b){
        System.out.println(b.getClass().getName());
        System.out.println(a.getClass().getName());
    }
}

Checkout Bounded Type Parameters or Bounded Types with Generics in Java

Sakibul Alam
  • 1,731
  • 2
  • 21
  • 40
  • Thank you @Sakibul , it is I was looking for and clear my concept also .. Thank you – voila Dec 11 '22 at 09:02
  • one more thing - Ideally, I am support to call pick function like this `new A().pick("abc","5") , it is right otherwise the way I have called it is raw type – voila Dec 11 '22 at 09:13
  • yes. you can call it that way. But the compiler is smart enough to infer the type most of the time. In this case, since both arguments are `String`s, the compiler would know the `T` is a `String`, so you can do `new A().pick("abc","5")` – Sakibul Alam Dec 11 '22 at 09:22
  • Above comment also makes sense .. Anyways thank you very much – voila Dec 11 '22 at 09:40