Generics

The main objective of generics is to resolve type casting problems i.e. to provide type-safety in the code.

What is type safety?
Suppose you want to store a list of a particular type of objects, say Employee.
Now lets consider 2 options : Arrays and ArrayLists.

You would store it in an array as follows :
Employee[] employees = new Employee[100];
employees[0] = new Employee(1, "Sandeep");
employees[1] = new Employee(1, "Ravi");
.......
and likewise.

Now if you try to use employees[10] = "Sandeep" i.e. try to store a string instead of an employee object; it should give a compile time error. Something similar to - Incompatible types : Expected Employee Got String.
Try this.

The point made here is that Arrays are type safe. Whenever we try to store anything except the type that the array was intended, it would result in a compilation error.

Now lets take the same example with ArrayList.
Store the list of employees in an arraylist as follows :

ArrayList employeeList = new ArrayList();
employeeList.add(new Employee(1, "Sandeep", "IT"));
employeeList.add(new Employee(2, "Ravi", "CE"));
employeeList.add(new Employee(3, "Alan", "IT"));
employeeList.add("Sandeep");

Now try to compile the code. This time it gets compiled successfully.

What this means is that while iterating through the list, there is no guarantee that the objects in the list are of the type Employee. You need to type cast it to the type Employee and you now will have an additional check to see if the object in the list is of the type Employee.

Try the following code :

for(int i=0; i<employeeList.size();i++) {
    System.out.println(((Employee) employeeList.get(i)).getId());}

This will give a runtime ClassCast exception when it doesnt find get the object of the type Employee.

To solve this, lets add a check as follows :

for(int i=0; i<employeeList.size();i++) {
    if(employeeList.get(i) instanceof Employee)
        System.out.println(((Employee) employeeList.get(i)).getId());}

So does that mean if we require type-safety, do we need to only use arrays?

There is an issue with arrays i.e. they are fixed-size.

Collections on the other hand are dynamically allocated. 

Sun introduced Generics in version 1.5.
And with the help of generics, we can achieve type-safety and solve type-casting issues with collections.

How Generics helps in this example :

ArrayList<Employee> employeeListGenerics = new ArrayList();employeeListGenerics.add(new Employee(1, "Sandeep", "IT"));employeeListGenerics.add(new Employee(2, "Ravi", "CE"));employeeListGenerics.add(new Employee(3, "Alan", "IT"));employeeListGenerics.add("Sandeep");
for(int i=0; i<employeeGenericsList.size();i++) {
    System.out.println(employeeListGenerics.get(i).getId());}

If you try the above code, you will get a compilation error saying that you do not have a add() method for String type.

Remove the line giving the compilation error, and run the program.

As we see, its type safe and we also need not require to type-cast while retreiving.

The code for the above examples can be found here.

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures