Java Program to store any type of variable in class and get it using generics.
Objective
Write a Java program to create a Generic Class that can store and retrieve any type of variable.
Algorithm / Approach
- Create a class
Test<T>. - Declare a private variable
xof typeT. - Provide a
set(T a)method to assign a value tox. - Provide a
get()method that returns typeT. - In main, create instances of
Testfor Integer, Float, and String.
Test.java
class Test<T> {
private T x;
void set(T a) {
x = a;
}
T get() {
return x;
}
}
class Demo {
public static void main(String[] a)
{
Test<Integer> t1=new Test<Integer>();
Test<Float> t2=new Test<Float>();
Test<String> t3=new Test<String>();
t1.set(5);
t2.set(8.5f);
t3.set("Alok");
System.out.println(t1.get());
System.out.println(t2.get());
System.out.println(t3.get());
}
}
Expected Output
5 8.5 Alok
Explanation of the Program
- This is a classic example of a Generic Container class.
- By using the type parameter
<T>, the class becomes completely agnostic to the data it holds. The compiler dynamically replacesTwith the actual Object type you specify during instantiation. - This provides strong Type Safety. If you create a
Test<Integer>, the compiler will instantly throw an error if you try to pass a String to theset()method.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)