Generic Class

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<>();
		Test<Integer> intTest = new Test<>();
		Test<Double> doubleTest = new Test<>();
class Test<T>{
	T item;

	public T getItem() {
		return item;

	public void setItem(T item) {
		this.item = item;
	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);
		Hashtable<String,String> h2 = new Hashtable<>("Ten","Ten");
class Hashtable<K,V>{
	private K k;
	private V v;
	Hashtable(K k,V v){
		this.k = k;
		this.v = v;
	public String toString(){
		return k.toString()+" - "+v.toString();

  • K – Key
  • E – Element
  • N – Number
  • T – Type
  • V – Value
  • S,U,V – Multiple Type

Leave a Comment