image.png

Generic Programming

Generic Methods

image.png

Generic methods are used to implement generic algorithms.

Example:

// non type-safe
void printArray(Object[] arr) {
    for(Object ele : arr)
        System.out.println(ele);
    System.out.println("Number of elements printed: " + arr.length);
}

// type-safe
<T> void printArray(T[] arr) {
    for(T ele : arr)
        System.out.println(ele);
    System.out.println("Number of elements printed: " + arr.length);
}

String[] arr1 = { "John", "Dagny", "Alex" };
printArray(arr1); // printArray<String> -- String type is inferred

Integer[] arr2 = { 10, 20, 30 };
printArray(arr2); // printArray<Integer> -- Integer type is inferred

Generics Limitations

  1. Cannot instantiate generic types with primitive Types. Only reference types are allowed.

    ArrayList<Integer> list = new ArrayList<Integer>(); // okay Array
    List<int> list = new ArrayList<int>(); // compiler error
    
  2. Cannot create instances of Type parameters.

    Integer i = new Integer(11); // okay 
    T obj = new T(); // error
    
  3. Cannot declare static fields with generic type parameters.

    class Box<T> {     
    	private T obj; // okay     
    	private static T object; // compiler error 
    	// ...
    }
    
  4. Cannot use casts or instanceof with generic Type params.

    if(obj instanceof T) {  // compiler error     
    	newobj = (T)obj;    // compiler error 
    }
    
  5. Cannot create arrays of generic parameterized Types

    T[] arr = new T[5]; // compiler error
    
  6. Cannot create, catch, or throw Objects of Parameterized Types

    throw new T(); // compiler error 
    try {     
    	// ... 
    } catch(T ex) { // compiler error     
    	// ... 
    }
    
  7. Cannot overload a method just by changing generic type. Because after erasing/removing the type param, if params of two methods are same, then it is not allowed.

    public void printBox(Box<Integer> b) {     
    	// ... 
    } 
    public void printBox(Box<String> b) { // compiler error     
    	// ... 
    }
    

Type Erasure

java-generics.png

Screenshot (1362).png