How can I assign a parameter in the Generic method to the Integer and Character classes at the same time?

Why does this code not show 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 regular 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 works fine, how can T be from the Integer class and the array T from the Character class at the same time, and if it starts then why it doesn't print true, ASCII vaue from 'a' 97, so it should print true

+7
java generics integer character
source share
1 answer

Since the compiler outputs Object as a type argument for your call

 Non_genre.genMethod(a, arr3) 

Inside the body of this method

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

your parameter of type T unlimited and therefore can only be considered 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) 
+6
source share

All Articles