Java Program to demonstrate generic Method.
Objective
Write a Java program to demonstrate a Generic Method that compares two generic objects.
Algorithm / Approach
- Create a generic container class
Test<T>. - In a separate
Democlass, create a static generic method:static <T> boolean comp(Test<T> t1, Test<T> t2). - Inside the method, use the
equals()method to compare the contained values. - In main, create two integer containers and two string containers, and pass them to
Demo.comp().
Test.java
class Test<T> {
private T x;
Test(T a){
x = a;
}
T get() {
return x;
}
}
class Demo {
static <T>boolean comp(Test<T> t1,Test<T> t2)
{
return t1.get().equals(t2.get());
}
}
class Main{
public static void main(String[] a)
{
Test<Integer> t1=new Test<Integer>(15);
Test<Integer> t2=new Test<Integer>(20);
Test<String> t3=new Test<String>("Alok");
Test<String> t4=new Test<String>("Alok");
boolean r1 = Demo.comp(t1, t2);
System.out.println("Result "+r1);
boolean r2 = Demo.comp(t3, t4);
System.out.println("Result "+r2);
}
}
Expected Output
Result false Result true
Explanation of the Program
- Just like classes, individual methods can also be generic. You declare a generic method by placing the type parameter
<T>before the return type. - The beauty of the
comp()method is that it enforces type matching: botht1andt2must be of the SAME generic typeT. You cannot accidentally compare aTest<Integer>with aTest<String>; the compiler will block it.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)