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

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

 

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
 

    • A Generic Class can be extended to create another Generic class
    • Generic interfaces can be created and used as follows
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 *