Generics Introduction

Array objects are by default type safe. i.e., we declare String Array we can insert only String Objects. By Mistake if we r trying to insert any other elements we will get compile time error.

E.g

String [] str = new String[100];
str[0] = "Ashok";
str[1] = 10; // C.E

But Collection objects are not type safe by default. If our requirement is to add only String objects to the ArrayList , By mistake if we r trying to insert any other element we won’t get any compile time error.

ArrayList list = new ArrayList();
list.add(β€œAshok”);
list.add(new Integer(10)); // No Compile Time Error.

While retrieving Array elements there is no need to perform typecasting.

String name = s[0]; // No typecasting required here.

But while retrieving the elements from ArrayList compulsory we should perform typecasting

String name = list.get(0); // C.E
String name = (String)list.get(0);

To resolve the above 2 problems (typesafety, typecasting) sun people introduced generics concept in the 1.5 version. If we want to create ArrayList object to hold any String Objects we have to define as follows.

ArrayList<String> list = new ArrayList<String>();

For this ArrayList we have to add only String objects. By mistake if we r trying to add any other type we will get compile time error.

list.add(β€œvalid”);
list.add(new Integer(10)); // C.E: Can’t find the symbol add(Integer)

At the time of retrieval no need to perform any typecasting.

String name = list.get(0); // No typecasting is required.

Hence by using generics we can provide type safety and we can resolve type casting problems.

By using generics we can define parameter for the collection. These parameterized collection classes are nothing but β€œGeneric collection classes”. Polymorphism concept is not applicable for the parameter type but applicable for base type.

List<String> list = new ArrayList<String>(); // Fine

List<Object> list = new ArrayList<String>(); // C.E: 
                                             Incompatable Types
                                             Found:ArrayList<String>
                                             Required :List<Object>

The type parameter must be object type(any class or interface name). we can’t apply generic concept for primitive datatype.

E.g

ArrayList<int> list = new ArrayList<int>(); // C.E: 
                                        unexpected type found : int
                                        Required : Integer

Generics Introduction


Scroll to top