Saturday, 12 September 2015

Generic Class Demo Example in java util package

class GenMap<T1,T2>
{
int index = -1;
Object a1[] = new Object[10];
Object a2[] = new Object[10];
void put(T1 obj1, T2 obj2)
{
index++;
a1[index] = obj1;
a2[index] = obj2;
}
T2 get(T1 key)
{
for(int i = 0; i <= index; i++)
{
if(a1[i].equals(key))
return (T2) a2[i];
}
return null;
}
void display()
{
for(int i = 0; i <= index; i++)
{
System.out.println(a1[i] + " : " + a2[i]);
}
}
}


class GenericDemo2
{ public static void main(String args[])
{ GenMap<String, String> gm = new GenMap<String, String>();
gm.put("Devesh", "Ramesh");
gm.put("Pawan", "Prakash");
gm.put("Naveen", "Narendra");
//gm.put("Neeraj", 2433);
System.out.println("Map entries: ");
gm.display();
String fname = gm.get("Pawan");
System.out.println("Pawan's father name: " + fname);

GenMap<String, Double> gm1 = new GenMap<String, Double>();
gm1.put("Devesh", 1000.0);
gm1.put("Pawan", 2000.0);
gm1.put("Naveen", 3000.0);
//gm1.put("Neeraj", "Mohan");
System.out.println();
System.out.println("Map entries: ");
gm1.display();
double balance = gm1.get("Pawan");
System.out.println("Pawan's balance is: " + balance);
}
}

No comments:

Post a Comment