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.

4

1 回答 1

6

因为编译器推断Object为您调用的类型参数

Non_genre.genMethod(a, arr3)

在该方法的主体内

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

您的类型参数T是无界的,因此只能视为Object.

由于x和 的元素y属于同一类型(T),因此可以很好地比较它们。

if (r == x)
于 2015-07-05T15:02:09.600 回答