Java Generics
Lecture Objectives
• To understand the objective of generic
programming
• To be able to implement generic classes and
methods
• To know the limitations of generic programming in
Java
• To understand the relationship between generic
types and inheritance
Introduction To Generics
• With Generics,you can define an algorithm
once,Independnently of any specific type of
data,and then apply that algorithm to a wide
variety of data types without any additional
effort.
• Through,the use of Generics It is possible to
create classes Interfaces and methods that will
work in a type safe manner with various kinds of
GENERICS
• Many Algorithms are logically the same,no
matter what type of data they are being applied
to.
• For example the Mechanism that supports a
stack is the same whether the stack is storing
Items of type Integer,String or Object .
• With Generics you can define an Algorithm
once,independnently of any specific type of data
and then apply the Algorithm to a wide variety of
data types without any additional effort.
What are Generics?
• The Term Generics means parameterized
types.Parameterized types are important
because they enable you to create
classes,Interface 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.
Why Generics?
• A class ,Interface or method that operates on a
parameterized type is called a Generic as in
Generic Class or Generic Method.
• Generics add the type safety that was
Lacking.They also streamline the
process,because it is no longer necessary to
explicitly employ casts to translate between
Object and the type of data that is actually
being operated upon.
Why Generics?
• With Generics all casts are automatic and
implicit.Thus,Generics expand your ability to
reuse code and let you do so safely and easily.
• Object is the superclass of all other classes.
• Thus the Generic methods use Object
References to operate on the type of objects.
A simple Generics Example?
• The showType() method displays the type of T by
calling getName() on the class object returned by
the call to getclass() on ob.
• The getclass() method is defined by Object and
is thus a member of class types.It returns a class
object that corresponds to the type of the class of
the object on which it is called.
• Gen<Integer> iob;
•
A Simple Generics Example
• First notice that the type Integer is specified
within the angle brackets after Gen.In this case
Integer is a type argument that is passed to Gen’s
type parameter,T
• Eg iob=new Gen<Integer>(88);
• Note that when the Gen constructor is called,the
type argument Integer is also specified.The
Reference by new must also be of type
Gen<Integer>. If it is’nt a compile time error will
result.
Generics
• iob=new Gen<Double>(88.0)
• Javac will type check because iob is of type
Integer.It can’t be used to refer to an object of
Gen<Double>.This is why Generics ensure
type safety.
• First notice how Gen is declared by the
following line.
• class Gen<T> {
Generics
• Here T is the name of type parameter.This name
is used as a placeholder for the actual type that
will be passed to Gen when a n object is created.
• Notice that T is used within <> .The syntax can
be generalized.
• Whenever a type parameter is being declared it
is specified within angle brackets.Because Gen
uses a type parameter,Gen is a generic class
which is also called a parameterized type.
Generics
• Next T is used to declare an object called ob as
shown here. T ob; //declare an object of type T.
• As explained T is a placeholder for the actual
type that will be specified when a Gen object is
created.
• Thus Ob will be an object of the type passed to
T.
• For example if type string is passed to T,then in
that instance ob will be of type string.
•
Generics
• Now consider Gen’s constructor
• Gen(T O) { ob=o;}
• Notice that its parameter O is of type T.This
means that the actual type of O is determined
by the type passed to T,when a Gen object is
created.
• Also because both parameter O and the
member variable ob are of type T, they will both
be of the same actual type when a Gen object is
created.
Generics
• The Type parameter T can also be used to
specify the return type of a method as it is the
case with the getob() method shown above.
• T getob() { return ob;}
• Because ob is also of type T,its type is
compatible with the return type specified by
getOb().
• The showType() method displays the type of T
by caling getName() class object returned by
the call to getclass() on ob.
Generics
• The getclass() method returns a class object
that corresponds to the type of class of the
object on which it is called.
• The GenDemo class demonstrates the generic
Gen class.It first creates a version of Gen for
intgers as shown here.
• Gen<Integer>iob;
• First notice that the type Integer is specified with
the angle brackets after Gen.
Generics
• In this case Integer is a type argument that is
passed to Gen’s type parameter T. This effectively
creates a version of Gen in which all references to
T are translated into reference to Integer.
• The next line assigns to iob a reference to an
Instance of an Integer version of the Gen class.
• iob=new Gen<Integer>(88); //Autoboxing
• Notice that when the Gen constructor is called
the type argument Integer is also specified.
Generics
• This is necessary because the type of the
object (in this case iob) Gen<Integer>.
• Thus the reference returned by new must also
be of type Gen<Integer>.
• If it is’nt a compile time error will result.For Eg
the following assignment will cause a compile
time error.
• iob=new Gen<Double>(99.0) //Error.!
• This type checking is one of the main benefits
of generic’s because it ensures type safety.
Generics
• The program then displays the type of ob within
iob,which is integer.Next the program obtains the
value of ob by use of the following line.
• int v=iob.getob();
• Because the return type of getob() is T,which
was replaced by Integer when iob was declared,
the return type of getOb() is also Integer,which
unboxes into int when assigned to v(which is an
int).
Generics
• However the auto-unboxing feature makes the
code more compact.Next GenDemo declares
an object of type Gen<String>.
• Gen<String> strob=new
Gen<String>(“Genericstype”);
• Because the type argument is String String is
substituted for T inside Gen.This creates a
String version of Gen as the remaining lines in
the program demonstrate.
Generics Work only with Objects.
• When declaring an Instance of 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.
• For Eg with Gen it is possible to pass any class
type to T,but you cannot pass a primitive type to
a type parameter.
• Gen<int> Strb=new Gen<int>(90);//Error can’t
use primitive type.
Generic Types Differ Based on their
Type Arguments
• A key point to understand about generics types
is that a reference of one specific version of a
generic type is not type compatible with another
version of the same generic type
• For eg, assuming the program just shown the
following line of code is in error and will not
compile.
• iob=strob; //Wrong.
Parameterized Classes and Generics
• The class ArrayList is a parameterized class
• It has a parameter, denoted by Base_Type, that
can be replaced by any reference type to obtain a
class for ArrayLists with the specified base type
• Starting with version 5.0, Java allows class
definitions with parameters for types
These classes that have type parameters are called
parameterized class or generic definitions, or, simply,
generics
Generics (Cont’d)
• A class definition with a type parameter is stored
in a file and compiled just like any other class.
• Once a parameterized class is compiled, it can be
used like any other class.
However, the class type plugged in for the type parameter
must be specified before it can be used in a program.
Doing this is said to instantiate the generic class.
Sample<String> object = new Sample<String>();
A Class Definition with a Type Parameter (Cont’d)
• A class that is defined with a parameter for a type
is called a generic class or a parameterized class
The type parameter is included in angular brackets after the
class name in the class definition heading.
Any non-keyword identifier can be used for the type
parameter, but by convention, the parameter starts with an
uppercase letter.
The type parameter can be used like other types used in
the definition of a class.
Tip: Compile with the -Xlint Option
• There are many pitfalls that can be encountered
when using type parameters
• Compiling with the -Xlint option will provide
more informative diagnostics of any problems
or potential problems in the code
javac –Xlint Sample.java
Thus for this declaration ob is of type Integer and
the return type of getob() is of type Integer.
A Generic Constructor Name Has No Type Parameter!!!
• Although the class name in a parameterized class definition has a
type parameter attached, the type parameter is not used in the
heading of the constructor definition:
public Pair<T>()
• A constructor can use the type parameter as the type for a parameter
of the constructor, but in this case, the angular brackets are not used:
public Pair(T first, T second)
• However, when a generic class is instantiated, the angular
brackets are used:
Pair<String> pair = new Pair<STring>("Happy", "Day");
A Primitive Type Cannot be Plugged in for a Type Parameter!!!
• The type plugged in for a type parameter must
always be a reference type:
It cannot be a primitive type such as int,
double, or char
However, now that Java has automatic boxing,
this is not a big restriction.
Note: Reference types can include arrays.
Limitations on Type Parameter Usage
• Within the definition of a parameterized class
definition, there are places where an ordinary
class name would be allowed, but a type
parameter is not allowed.
• In particular, the type parameter cannot be used in
simple expressions using new to create a new
object
For instance, the type parameter cannot be used as a
constructor name or like a constructor:
T object = new T();
T[] a = new T[10];
Limitations on Generic Class Instantiation
• Arrays such as the following are illegal:
Pair<String>[] a =
new Pair<String>[10];
• Although this is a reasonable thing to want to
do, it is not allowed given the way that Java
implements generic classes
Using Generic Classes and Automatic Boxing
Using Generic Classes and Automatic Boxing (Cont’d)
Program Output:
Multiple Type Parameters
• A generic class definition can have any number
of type parameters.
Multiple type parameters are listed in angular
brackets just as in the single type parameter case,
but are separated by commas.
Multiple Type Parameters (Cont’d)
Multiple Type Parameters (Cont’d)
Generic Methods
• When a generic class is defined, the type
parameter can be used in the definitions of the
methods for that generic class.
• In addition, a generic method can be defined that
has its own type parameter that is not the type
parameter of any class
A generic method can be a member of an ordinary class or a
member of a generic class that has some other type
parameter.
The type parameter of a generic method is local to that
method, not to the class.
Generic Methods (Cont’d)
• The type parameter must be placed (in angular
brackets) after all the modifiers, and before the
returned type:
public static <T> T genMethod(T[] a)
• When one of these generic methods is invoked, the
method name is prefaced with the type to be
plugged in, enclosed in angular brackets
String s = NonG.<String>genMethod(c);