7

Why this code isn't showing any compilation error?

public class Generic
{
    public static void main(String[] args)
    {
        Character[] arr3={'a','b','c','d','e','f','g'};
        Integer a=97;
        System.out.println(Non_genre.genMethod(a,arr3));
    }
}

class Non_genre
{
    static<T> boolean genMethod(T x,T[] y)
    {
        int flag=0;
        for(T r:y)
        {
            if(r==x)
                flag++;
        }
        if(flag==0)
            return false;
        return true;
    }
}

If we write a normal code like this(shown below)

public class Hello
{
    public static void main(String[] args)
    {
        Character arr=65;
        Integer a='A';
        if(arr==a)  //Compilation Error,shows Incompatible types Integer and Character
            System.out.println("True");
    }
}   

Then why the above above is running fine,how can T be of Integer class and array of T be of Character class at the same time,and if its running then why its not printing true,ASCII vaue of 'a' is 97,so it should print true.

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42

1 Answers1

6

Because the compiler infers Object as a type argument for your invocation of

Non_genre.genMethod(a, arr3)

Within the body of that method

static <T> boolean genMethod(T x, T[] y) {

your type parameter T is unbounded, and so can only be seen as an Object.

Since x and the elements of y are of the same type (T), they can be compared just fine.

if (r == x)
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • *You can compare Object values to other Object values just fine*. This sounds a bit incorrect. It should be *You can compare references to each other just fine* – Chetan Kinger Jul 05 '15 at 15:05
  • @Sotirios-But what will be the type of T in for-each loop,and why its printing false? – Frosted Cupcake Jul 05 '15 at 15:05
  • 1
    @RajMalhotra Because you are using `==`. That checks for identity, not equality. – Chetan Kinger Jul 05 '15 at 15:05
  • @RajMalhotra The type of `T` is `T`. Since it has no bounds, you can only view it as an `Object`, ie. only `Object`'s methods are available. – Sotirios Delimanolis Jul 05 '15 at 15:09
  • 1
    If you want type checking to work properly you can call it like this. Non_genre.genMethod(a, arr3) which will give you an error as you have now hinted to the compiler that T is an Integer which means arr3 can only be an Integer[] – tobad357 Jul 05 '15 at 15:21
  • @ChetanKinger: The type `Object` is a reference type, so that is redundant – newacct Jul 05 '15 at 21:24
  • @newacct So you are saying that the statement *You can compare Object values to other Object values just fine* is correct? – Chetan Kinger Jul 06 '15 at 15:11