11:57 PM
0

                
we are  already well known about newly added concept in Java 1.5 i e.. Generics.
In Generics concept,we have to see how the classes were defined.

In normal ArrayList class up to 1.4 version of Java is defined like

class ArrayList
{
add(Object o);
Object get(int index);
.
.
.
}

Here we have to observe two things, those are 


In first method add(Object o) the argument passed is Object.we can give any type of Object to add into ArrayList. So we are loosing type safety here in this method.

ex:
a.add(Object o);
a.add(new Integer(10));

In the second method the return type of get(int index) method is Object.so the returning element may be any type of Object.So we have to perform type casting when ever we want to used that Object.

ex :
String name = (String )l.get(0);//here type casting is mandatory

due to this, at the time of retrieval it is compulsory to perform typecasting but from 1.5 version onwards a Generic version on ArrayList class is defined as follows:

syntax:
class ArrayList<T>
{
add(T t);
T get(int index);


if we want to define a ArrayList to hold String objects only then we will create a ArrayList as follows

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

For this compiler considerd ArrayList as follows:

class ArrayList<String>
{
add(String s);
String get(int index);
}

The argument to add() is String hence we can add only String type of Objects to the list:

ex:
l.add("face");
l.add("fact");
l.add(new Integer(10));//compile time error

i.e Through generics we are type safety.

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

i.e Through generics we can resolve type casting problems also.

By using generics we are associating type parameter for the classes.such kind of parameterized classes are called 
Generic classes.


0 comments:

Post a Comment