Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a parameter in a Generic method be assigned to an Integer and a Character class at the same time?

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.

like image 861
Frosted Cupcake Avatar asked Jul 05 '15 14:07

Frosted Cupcake


People also ask

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

Can a generic class definition can only have one type parameter?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

What kind of parameter type is used for a generic class to return and accept any types of Object?

Which of these type parameters is used for a generic methods to return and accept any type of object? Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

What can a generic class be parameterized for?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

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)
like image 78
Sotirios Delimanolis Avatar answered Nov 09 '22 14:11

Sotirios Delimanolis