How to write a Generic Class?
- Generic is identified by <T>, it is not necessary to be T but any alphabets. We take T commonly in the examples to suggest T as Types
- If a Data Member(not member function) is a class uses a Generic Data member then its class name show be followed by name of the generic types inside an diamond operator.
Example :
class GenericClass<A,B,C>{
A varA;
B varB;
C varC;
}
Example : On how a single classes variable can store different datatype
package com.test;
public class Demo {
public static void main(String[] args) {
Test<String> stringTest = new Test<>();
stringTest.setItem("Hello");
System.out.println(stringTest);
Test<Integer> intTest = new Test<>();
intTest.setItem(50);
System.out.println(intTest);
Test<Double> doubleTest = new Test<>();
doubleTest.setItem(50.55);
System.out.println(doubleTest);
}
}
class Test<T>{
T item;
public T getItem() {
return item;
}
public void setItem(T item) {
this.item = item;
}
@Override
public String toString() {
return this.item.toString();
}
}
Example : Multiple Parameters
package com.test;
public class DemoHashTable {
public static void main(String[] args) {
Hashtable<String,Integer> h1 = new Hashtable<>("Ten",10);
System.out.println(h1);
Hashtable<String,String> h2 = new Hashtable<>("Ten","Ten");
System.out.println(h2);
}
}
class Hashtable<K,V>{
private K k;
private V v;
Hashtable(K k,V v){
this.k = k;
this.v = v;
}
@Override
public String toString(){
return k.toString()+" - "+v.toString();
}
}
- K – Key
- E – Element
- N – Number
- T – Type
- V – Value
- S,U,V – Multiple Type