Generics in Java

Generics

  • Many algorithms work in a similar way irrespective of the data types on which they are applied on
    • All Stacks work in a similar way irrespective of the type of object they hold
  • Generics help to write algorithms independent of a data type
    • These algorithms can be applied to a variety of data types
    • The data type is parameterized
    • A class, interface or a method that works on a parameterized type is called a generic
    public class List<T>{
    	protected T [] list;
    	public List(T [] list){
    		this.list = list;
    	}
    	public void put(T element, int position){
    		list[position] = element;
    	}
    	public T get(int position){
    		return list[position];
    	}
    }
    

In above code, T represents a data type. While declaring an object of List, the programmer can decide the actual type for T.

List<String> list = new List<String>(new String[5]);
list.put("Hello", 0);
list.put("Welcome", 1);
list.put("Ok", 2);
System.out.println(list.get(0));
System.out.println(list.get(1));
System.out.println(list.get(2));

 

Just like String objects are stored and retrieved in the above example, the List class can be used for any kind of object

    • A generic can restrict the type of object that can be used as the parameter
      • A generic List class that performs arithmetic operations on the elements may want to restrict the parameters to Integer, Float, Double etc
      • Number is the super class of all the numeric wrapper classes
    • Only Number or its sub classes can be used as a parameter to List
    • Wildcards can be used with the Generic and Wildcards also can be bounded
public double getSum(List<? extends Double> list){
		//Code goes here
}

 

    • A Generic Class can be extended to create another Generic class
public class LinkedList<T> extends List<T>{
		//Code goes here
}
    • Generic interfaces can be created and used as follows
	interface List<T>{
		public void put(T element, int position);
		public T get(int position);
	}

	class LinkedList<T> implements List<T>{
		//Implementation goes here
	}

Generic Restrictions

  • A type parameter cannot be instantiated
  • T t1 = new T(); //Error, this will not work
  • T [] t2 = new T[5]; //Error, this will not work
  • A static method of a generic class cannot use the parameterized type
  • A generic class cannot extend Throwable
    • We cannot have generic exception classes

 

One thought on “Generics in Java

  1. furtdso linopv says:

    Hey very cool web site!! Man .. Beautiful .. Amazing .. I will bookmark your site and take the feeds also…I’m happy to find so many useful info here in the post, we need develop more strategies in this regard, thanks for sharing. . . . . .

Leave a Reply

Your email address will not be published. Required fields are marked *