12:20 AM
0




Collections is  main useful concept in java. But whenever we are adding different types of objects into a Collection Object we will face some problems in retrieving like type casting.In order to solve those problem a new concept was introduced in Java 1.5 i.e Generics.

The main objectives of Generics are:

1.To provide type safety for Collection Object
2.To resolve type casting problems.


1. providing type safety for Collection Object :

Before going to Collections directly we will talk about Arrays first.
All you know about Arrays very well.
Arrays are always type safe i.e. means In array we can add only single type of  elements.

ex:

String s [] = new String[5];
For this array we can add only String type of objects.if you are trying to add any other type of objects into this array it will give compile time error.

s[0]="face"
s[1]="fact"
s[2]=new Integer(78);//--- compile time error like Incompatible types

From this example we can say Arrays are type safe.
But Collections are not like Arrays,those are not type safe.

ex:

if your requirement is to hold only String type of objects then we can choose ArrayList.

ArrayList al = new ArrayList();

for this ArrayList object we can add any type of objects so it may fail at run time.
al.add("face");
al.add("fact");
al.add("new Integer(10)");// it compiles fine and executes fine.But our requirement fails here.


2.Resolve type casting problems:

Again we are taking example as arrays,
In case of arrays while retrieving elements,it is not required to perform type casting.we can easily perform next operations with retrieved elements.But in case of Collection we can't say surely that there is no need of type casting.

ex:

String s[] = new string[100];

s[0]="face";
s[1]="fact";
String name=a[0];
String name1= a[1];

But in case of Collection while retrieving elements type casting is mandatory.

ArrayList al = new ArrayList();
a.add("face");
a.add("fact");

String name = l.get(0);//compile time error
we cant assign directly to string , we have to type cast.

String name = (String)l.get(0);

type casting is main problem in Collections.
To resolve above to problem the Generics concept is introduced in 1.5 version of Java.

By using Generics we can define ArrayList to hold only String objects defined below

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

For this ArrayList we can add only String object so that we can add only String objects.By mistake if you try to add any different type of objects then it will not allow you to add into ArrayList..

ex:

al.add("face");
al.add("fact");
al.add("new Integer(10)");//compile time error 

i.e Through generics we are providing type safety for the Collection object 

At the time of retrieving objects it is not required to perform type casting also.

String name1 = l.get(0);// executes fine 

i.e Through this generics we are resolving Type casting problem in Collections.
















0 comments:

Post a Comment