Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate generic Method.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate generic Method.

Objective

Write a Java program to demonstrate a Generic Method that compares two generic objects.

Algorithm / Approach

  1. Create a generic container class Test<T>.
  2. In a separate Demo class, create a static generic method: static <T> boolean comp(Test<T> t1, Test<T> t2).
  3. Inside the method, use the equals() method to compare the contained values.
  4. 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 &lt;T&gt; before the return type.
  • The beauty of the comp() method is that it enforces type matching: both t1 and t2 must be of the SAME generic type T. You cannot accidentally compare a Test&lt;Integer&gt; with a Test&lt;String&gt;; the compiler will block it.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT