Java Generics
Java Generics
Lecture Objectives
• To understand the objective of generic programming
Throws ClassCastException at runtime because we are trying to cast Object in the list
to String whereas one of the element is of type Integer
• Define our own classes with generics type.
• A generic type is a class or interface that is parameterized
over types.
• Use angle brackets (<>) to specify the type parameter.
Use java generic class to rewrite
• Notice the use of GenericsType class in the main method.
• Don’t need to do type-casting and can remove ClassCastException at
runtime.
• Don’t provide the type at the time of creation, the compiler will
produce a warning that “GenericsType is a raw type.
• References to generic type GenericsType<T> should be
parameterized”.
• When don’t provide the type, the type becomes Object and hence it’s
allowing both String and Integer objects.
• But, should always try to avoid this because we will have to use type
casting while working on raw type that can produce runtime errors.
Parameterized Classes and Generics
Generics (Cont’d)
• A class definition with a type parameter is stored in a file and
compiled just 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.
Program Output:
Limitations on Type Parameter Usage
Using Generic Classes and Automatic Boxing
Using Generic Classes and Automatic Boxing (Cont’d)
Program Output:
Multiple Type Parameters
Multiple Type Parameters (Cont’d)
Multiple Type Parameters (Cont’d)
Using a Generic Class with Two Type Parameters
Program Output:
Bounds for Type Parameters
Bounds for Type Parameters (Cont’d)
It can’t be used to compare
the
average of an object of type
Stats<Double> with the
average of an object of type
write a method that displays the X and Y coordinates for each
element in the coords array of a Coords object.
Generic Interfaces
if a class implements a
generic interface, then
that class must also be
generic,
at least to the extent
that it takes a type
parameter that is passed
to the interface.
• class MyClass implements MinMax<T> { // Wrong