Saturday, November 28, 2015

Generics in Java with examples

Generics in java:

Generics were Introduced in as one of the features in JDK 5. I will be covering everything i find useful with java generics and related to them.Java Generics are a language feature that allows for definition and use of generic types and methods.

Why Generics in Java:
Array Objects are by default type-safe. i.e. we can declare String array and we can insert only String Objects.By mistaking we are trying to insert any other elements we will get compile time error.
Ex:
String [] s=new String[100];
s[0]="lucky";
s[1]=10;//raised compile time error

But collection objects are not typesafe by default. If our requirement is to add only String Objects to the ArrayList, By Mistake if we are trying to insert any other element we won't get any compile time error.
Ex:
ArrayList al=new ArrayList();
al.add("lucky");
al.add(new Integer(10));//no compile time error

While retrieving array elements there is no need to perform typecasting
Ex:
String name=s[0];//typecasting not required here

But while retrieving array elements from ArrayList we should  perform typecasting.

Ex:
String name=al.get[0];//compile time error
String name=(String)al.get[0]// no compile time error

So you people understand what problems we facing here, so to resolve above two problems(typesafety,typecasting) sun people introduced Generics concept in the JAVA 1.5 version.

If we want create ArrayList object to hold any String objects we have to define as fallows.

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

For this ArrayList  we can add only String Objects,by mistake if we are trying to add any other type elements we will get compile time error.

EX:
al.add("lucky");
al.add(new Integer(10));//compile time error

It show compile time error like "can't find the symbol add(Integer)
At that time of retrieval  no need to perform any typecasting.

Ex:
String name=al.get[0];//no typecasting required here

NOTE:

Hence by using generics we can provide typesafety and we can resolve typecasting problems..

Parameter Generics in java:

By using  generics we can define parameter for the collection. These parameterized collection classes are nothing but "Generic Collecton classes"

Note:

Polymorphism concept not applicable for parameter type but applicable for base type.

EX 1:

  


Ex 2:









The type  parameter must be Object type(any class or interface name).
We can't apply generic  concept for Primitive datatype.


Ex:- 

ArrayList<int> l = new ArrayList<int>();



C.E:- unexpected type found : int
Required : Integer


Generic Class

Until java 1.4 version we have ArrayList class with the  declaration as fallows.

Class ArrayList{
add(Object 0);
Object.get(int index);
}
Her add method contain Object as an argument,hence we can add any type of object.
But we can not get any type safety. The return type of get() method is object hence at the time of retrieval we should perform typecasting.

But in the Java 1.5 version we have generics ArrayList class with definition as follows;

Ex:

Class ArrayList<T >{
add(T t);
T get(int);

Based on runtime requirement the corresponding version of ArrayList will loaded.

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

For the fallowing declaration the corresponding loaded class is:

Class ArrayList<String>{
add(String);
String get(int);
}
Note:

The argument to the add method is String hence we should add only String Object as the result we will get type safety.
The return type of get() method is String. Hence at the time of retrieval no need to perform typecasting.

We can get our own Generic class also

Ex:

class gen<T>
{
T ob;
gen(T ob)
{
this.ob = ob;
}
public void show()
{
System.out.println("The type of Object is : "+ob.getClass().getName());
}
public T getOb()
{
return ob;
}
}
class GenericsDemo
{
public static void main(String[] args)
{
gen<String> g1 = new gen<String>("lucky");
g1.show();
System.out.println(g1.getOb());
gen<Integer> g2 = new gen<Integer>(10);
g2.show();
System.out.println(g2.getOb());
}
}
Output:
The type of Object is : java.lang.String
lucky

Bounded Types:
we can bound the type of parameter for a particular range.Such type of  types is called"Bounded Types".

we can achieve this by using extends Keyword.

Ex:
class Gen<T>
{
}

Here we can pass any types as the type parameter and there are no restrictions.

Gen<String> g1 = new Gen<String>();//applicable
Gen<Integer> g2 = new Gen<Integer>();//applicable


In generics we have only extends keyword and there is no implements keyword. It’s purpose is also survived by using extends keyword only.

Ex:

class Gen<T extends Number>
{
T ob;
Gen(T ob)
{
this.ob = ob;
}
void show()
{
System.out.println("The int value is :" + ob.intValue());
}
}
class GenDemo
{
public static void main(String arg[])
{
Gen<Integer> t1 = new Gen<Integer>(new Integer(10));
t1.show();
Gen<Double> t2 = new Gen<Double>(10.5);
t2.show();
Gen<String> t3 = new Gen<String>("raju");
t3.show();
}
}

Generic Methods:

1) m1(ArrayList<String>)
   
   It is applicable for ArrayList of only String type.

2) m1(ArrayList<? extends x> l)

Here if ‘x’ is a class then this method is applicable for ArrayList of either x or it’s child             classes.
If ‘x’ is an interface then this method is applicable for ArrayList of any implementation           class of x

3) m1(ArrayList <? Super x> l)

If ‘x’ is a class then this method is applicable for ArrayList of either x or it’s super classes.

If ‘x’ is an interface then this method is applicable for ArrayList of any super classes of implemented
class of x.

4) m1(ArrayList <?> l)

This method is applicable for ArrayList of any type.

In the method declaration if we can use ‘?’ in that method we are not allowed to insert any element except null. Because we don’t know exactly what type of object is coming.

EX:


class Test

{
public static void main(String arg[])
{
ArrayList<String> l1 = new ArrayList<String>();
l1.add("A");
l1.add("B");
l1.add("C");
l1.add("D");
m1(l1);
ArrayList<Integer> l2 = new ArrayList<Integer>();
l2.add(10);
l2.add(20);
l2.add(30);
l2.add(40);
m1(l2);
}
public static void m1(ArrayList<?> l)
{
//l.add("D");//compile time error  Because we can’t expect what type of value
will come
l.remove(1);
l.add(null);
System.out.println(l);
}
}

Output:

[A, C, D, null]
[10, 30, 40, null]













No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...