JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com





Get Best Tutorial on all major programing language



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Generic Framework:

Overview

Generics are a powerful extension to Java because they streamline the creation of type-safe,
reusable code.

What Are Generics?
  • Generics means parameterized types. 
  • Parameterized types are important because they enable you to create classes, interfaces, and
    methods in which the type of data upon which they operate is specified as a parameter.
  •  Using generics, it is possible to create a single class, for example, that automatically
    works with different types of data.
  •  A class, interface, or method that operates on a parameterized type is called generic,
    as in generic class or generic method.

Benefits
  • Provides compile-time type safety
  • Eliminates the need for casts
The General Form of a Generic Class

//Here is the syntax for declaring a generic class:
class class-name<type-param-list> // ...

//Here is the syntax for declaring a reference to a generic class:

class-name<type-arg-list> var-name =
new class-name<type-arg-list>(cons-arg-list)

A simple Generic Example
  • T is a placeholder for the actual type that will be specified when a Gen object
    is created
  •  if type String is passed to T, then in that instance, ob will be of type String.
// A simple generic class.
// Here, T is a type parameter that
// will be replaced by a real type
// when an object of type Gen is created.
class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
// Show type of T.
void showType() {
System.out.println("Type of T is " +
ob.getClass().getName());
}
}


// Demonstrate the generic class.
class GenDemo {
public static void main(String args[]) {
// Create a Gen reference for Integers.
Gen<Integer> iOb;
// Create a Gen<Integer> object and assign its
// reference to iOb.  Notice the use of autoboxing
// to encapsulate the value 88 within an Integer object.
iOb = new Gen<Integer>(88);
// Show the type of data used by iOb.
iOb.showType();
// Get the value in iOb. Notice that
// no cast is needed.
int v = iOb.getob();
System.out.println("value: " + v);
System.out.println();
// Create a Gen object for Strings.
Gen<String> strOb = new Gen<String>("Generics Test");
// Show the type of data used by strOb.
strOb.showType();
// Get the value of strOb. Again, notice
// that no cast is needed.
String str = strOb.getob();
System.out.println("value: " + str);
}
}

Output

java GenDemo
Type of T is java.lang.Integer

value: 88
Type of T is java.lang.String
value: Generics Test
Download Code

Generics Work Only with Objects
  • When declaring an instance of a generic type, the type argument passed to the type parameter
    must be a class type.
  • You cannot use a primitive type, such as int or char.

Generic Collections API



Compile Time vs. Runtime Safety

Before Generic

GenericsWarning.java
ArrayList list = new ArrayList();
list.add(0new Integer(42));
int total = ((Integer)list.get(0)).intValue();

CompilerWarnings
javac GenericsWarning.java
Note: GenericsWarning.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

After Generic
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0new Integer(42));
int total = list.get(0).intValue();
Compile time error
javac -Xlint:unchecked GenericsWarning.java
GenericsWarning.java:7: warning: [unchecked] unchecked call to add(int,E)
as a member of the raw type java.util.ArrayList
    list.add(0, new Integer(42));
            ^
1 warning

Example:- Without Generics

import java.util.*;

class AHash{

 public static void main(String args[]){

 Map s=new HashMap();
 s.put("1","one");
 s.put("3","three");
 s.put("2","two");
 s.put("5","five");
 s.put("6","six");
 System.out.println(s);
  }

}

Output:-

javac AHash.java
Note: GenericsWarning.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

java AHash
{3=three, 2=two, 1=one, 6=six, 5=five}

Download Code


Example:-1    With Generics
  • We define a generic class that takes a type parameter 
  • When a generic is instantiated, the actual type parameters are substituted
    for the formal type parameters.
import java.util.*;

public class ArrayListGenericDemo {
  public static void main(String[] args) {
    ArrayList<String> data = new ArrayList<String>();
    data.add("Raj");
    data.add("Kumar");

    // data.add(new Date()); This won't compile!

    Iterator<String> it = data.iterator();
    while (it.hasNext()) {
      String s = it.next();
      System.out.println(s);
    }
  }
}

Output:-

javac ArrayListGenericDemo.java
java ArrayListGenericDemo
Raj
Kumar
Download Code

Example:-2

class MyGen1<T,V>{

   T ob1;
   V ob2;
  
   MyGen1(T ob1, V ob2){
    this.ob1=ob1;
    this.ob2=ob2;
   }
   
   MyGen1(){
    this.ob1=null;
    this.ob2=null;
   }

   void show(){
     System.out.println(ob1.getClass().getName());
     System.out.println(ob2.getClass().getName());

   }
}

class MyGenerics{
  public static void main(String args[]){
    MyGen1<Integer, String> MyGenObj1 = new MyGen1<Integer, String>(100,"Hello");
    MyGen1<Integer, String> MyGenObj3 = new MyGen1<Integer, String>();
    MyGenObj1.show();    

   }
}

Output:-

javac MyGenerics.java
java MyGenerics
java.lang.Integer
java.lang.String

Download Code

Bounded Parameterized Types
  • The <E extends Number> syntax means that the type parameter of MathBox
    must be a subclass of the Number class
  • The type parameter is bounded
    • new MathBox<Integer>(5); //Legal
    • new MathBox<Double>(32.1); //Legal
    • new MathBox<String>(“No good!”);//Illegal
  • Inside a parameterized class, the type parameter serves as a valid type.
  • Java allows multiple inheritance in the form of implementing multiple interfaces,
    so multiple bounds may be necessary to specify a type parameter.
  •  The following syntax is used then:
    <T extends A & B & C & …>


Example:-3

class MyGen<T extends Number>{

   T ob;

   MyGen(T ob){
    this.ob=ob;
   }

   MyGen(){
    this.ob=null;
   }

   void show(){
     System.out.println(ob.doubleValue());
   }

}

class MyGenBounded{
  public static void main(String args[]){
    MyGen<Float> MyGenObj = new MyGen<Float>(100f);
    MyGenObj.show();    

   }
}

Output:-

javac MyGenBounded.java
java MyGenBounded
100.0


Download Code

Generics and Inheritence
  • Suppose you want to restrict the type parameter to express some
    restriction on the type parameter
  • This can be done with a notion of subtypes
  • Subtypes can be expressed in Java using inheritence


Example:-4

class A{
 int x=10;
}

class extends A{
 int x=20;

}

class extends B{
 int x=30;

}

class MyGen2<T extends A>{
   T myG;

   MyGen2(T myG){
     this.myG = myG;
    }

   MyGen2(){
     this.myG = null;
    }

  }

class MyGenBoundedSuper{

  public static void show(MyGen2<? super A> m){
    System.out.println(m.myG.x);    
    }

 public static void main(String args[]){
  A aObj = new A();
  MyGen2<A> genObj = new MyGen2<A>(aObj);  
  show(genObj);
  }
}


  

Output:-

javac MyGenBoundedSuper.java
java MyGenBoundedSuper
10

Download Code

Generics And Wildcards

Consider the following code:-
  • We want a method that prints our all the elements of a collection
without Generic
void printCollection(Collection c) { 
  Iterator i = c.iterator();
  for (k = 0; k < c.size(); k++) {   
         System.out.println(i.next());
  }
}

with generics

void printCollection(Collection<Object> c) { 
  for (Object e : c) { 
    System.out.println(e);
  }
}

printCollection(stones); //won't compile
  • The problem is that this new version is much less useful than the old one. 
  • The old code could be called with any kind of collection as a parameter, 
  • The new code only takes Collection<Object>, which, as  is not a supertypeof all kinds of collections!
Using Wildcards

Collection<?>
  •  Pronounced “collection of unknown” and denoted Collection<?>, 
  • “collection of unknown” is a collection whose element type matches
    anything — a wildcard type
  • A collection whose element type matches anything.
  •  It’s called a wildcard type for obvious reasons.
void printCollection(Collection<?> c) { 
  for (Object e : c) { 
    System.out.println(e);
  }
}

Pitfalls of wildcards
String myString;
Object myObject;
List<?> c = new ArrayList<String>();

// c.add("hello world");       // compile error
// c.add(new Object());       // compile error
((List<String>c).add("hello world");
((List<Object>c).add(new Object());  // no compile error!

// String myString = c.get(0);    // compile error
myString = (Stringc.get(0);
myObject = c.get(0);
myString = (Stringc.get(1);     // run-time error!

Some Generic Restrictions
  • Type Parameters Can’t Be Instantiated
    • It is not possible to create an instance of a type parameter
// Can't create an instance of T.
class Gen<T> {
T ob;
Gen() {
ob = new T()// Illegal!!!
}
}

  • Restrictions on Static Members
    • No static member can use a type parameter declared by the enclosing class.
class Wrong<T> {
// Wrong, no static variables of type T.
static T ob;
// Wrong, no static method can use T.
static T getob() {
return ob;
}
// Wrong, no static method can access object
// of type T.
static void showob() {
System.out.println(ob);
}
}
  • Generic Array Restrictions
    • You cannot instantiate an array whose base type is a type parameter
    • You cannot create an array of type-specific generic references
// Generics and arrays.
class Gen<T extends Number> {
T ob;
T vals[]// OK
Gen(T o, T[] nums) {
ob = o;
// This statement is illegal.
// vals = new T[10]; // can't create an array of T
// But, this statement is OK.
vals = nums; // OK to assign reference to existent array
}
}
class GenArrays {
public static void main(String args[]) {
Integer n[] 1234};
Gen<Integer> iOb = new Gen<Integer>(50, n);
// Can't create an array of type-specific generic references.
// Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong!
// This is OK.
Gen<?> gens[] new Gen<?>[10]// OK
}
}





  • Generic Exception Restriction
    • A generic class cannot extend Throwable.
    • You cannot create generic exception classes.