Generics


Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, etc., and user-defined types) to be a parameter to methods, classes, and interfaces. For example, classes (like HashSet, ArrayList, or HashMap) use generics very well.

Generic Classes
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax:
   BaseType<Type> obj = new BaseType<Type>( )
In parameter type, we can not use primitives like int, char, or double.

Generics.java (generic classes)
// To show how a user-defined generic class works  
class Generics {
  // The driver method 
  public static void main( String[ ] args ) { 
    // Instance of Integer type 
    Test<Integer> iObj = new Test<Integer>( Integer.parseInt( args[0] ) ); 
    System.out.print( iObj.getObject( ) + ": " ); 
    // Instance of String type 
    Test<String> sObj = new Test<String>( args[1] ); 
    System.out.print( sObj.getObject( ) + " year" ); 
  } 
}

// We use < > to specify the parameter type.
class Test<T> { 
  // An object of type T is declared 
  T obj; 
  Test( T obj ) { this.obj = obj; }   // constructor 
  public T getObject( ) { return this.obj; } 
}
shell> java Generics  (integer)   (string)

Output:           Result:

We can also pass multiple type parameters in generic classes.

MultipleTypes.java (multiple type parameters in generics)
// To show multiple type parameters in Java generics 
class MultipleTypes { 
  // The driver method
  public static void main ( String[ ] args ) { 
    Test<Integer, String> obj = new Test<Integer, String>( 
      Integer.parseInt( args[0] ), args[1] ); 
    obj.print( ); 
  } 
}

// We use < > to specify parameter type. 
class Test<T, U> { 
  // Two member attributes
  T obj1;   // An object of type T 
  U obj2;   // An object of type U 

  // Constructor 
  Test( T obj1, U obj2 ) { 
    this.obj1 = obj1; 
    this.obj2 = obj2; 
  } 

  // To print objects of T and U 
  public void print( ) { 
    System.out.print( obj1 + ": " ); 
    System.out.print( obj2 + " year" ); 
  } 
}
shell> java MultipleTypes  (integer)   (string)

Output:           Result:




      “You yourself, as much as anybody in the entire universe,    
      deserve your love and affection.”    
      ― Sharon Salzberg