Home > other >  Java generic method is holding two different type of values
Java generic method is holding two different type of values

Time:12-11

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.

CodePudding user response:

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

  •  Tags:  
  • java
  • Related