Unit 51
Unit 51
5: GENERICS
Contents
5.0. Aims and Objectives
5.1. Introduction to Generic Methods
5.2. Generic Classes
5.3. Summary
5.4. Model Examination Questions
This unit discusses the properties and roles of generics, generic methods and their rules to
define and use them. We will also discuss the generic classes with sample programs.
After you have studied this unit, you will be able to:
1
5.1. INTRODUCTION TO GENERIC
GENERIC METHODS
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively. Generics also provide compile-time type safety that allows
programmers to catch invalid types at compile time. Using Java Generic concept, we might
write a generic method for sorting an array of objects, then invoke the generic method
with Integer arrays, Double arrays, String arrays and so on, to sort the array elements.
Generics in Java is similar templates in C++ The idea is to allow type (Integer, String, … etc
and user defined types) to be a parameter to methods, classes and interfaces. For example,
classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for
any type.
Generic Methods:
Generic methods are methods that introduce their own type parameters. This is similar to
declaring a generic type, but the type parameter's scope is limited to the method where it is
declared. Static and non-static generic methods are allowed, as well as generic class
constructors.
The syntax for a generic method includes a list of type parameters, inside angle brackets,
which appears before the method's return type. For static generic methods, the type
parameter section must appear before the method's return type.
The Util class includes a generic method, compare, which compares two Pair objects:
2
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
The type has been explicitly provided, as shown in bold. Generally, this can be left out and
the compiler will infer the type that is needed:
This feature, known as type inference, allows you to invoke a generic method as an
ordinary method, without specifying a type between angle brackets.
You can write a single generic method declaration that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. Following are the rules to define
Generic Methods:
• All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next
example).
3
• Each type parameter section contains one or more type parameters separated by
commas. A type parameter, also known as a type variable, is an identifier that
specifies a generic type name.
• The type parameters can be used to declare the return type and act as placeholders
for the types of the arguments passed to the generic method, which are known as
actual type arguments.
• A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double
and char).
Example
Following example illustrates how we can print an array of different type using a single
Generic method:
System.out.println();
Integer[] intArray = { 1, 2, 3, 4, 5 };
4
System.out.println("Array integerArray contains:");
Output
We can also write generic functions that can be called with different types of arguments
based on the type of arguments passed to generic method, the compiler handles each
method.
// A Simple Java program to show working of user defined
// Generic functions
class Test
{
// A Generic method example
static <T> void genericDisplay (T element)
{
System.out.println(element.getClass().getName() +
" = " + element);
}
// Driver method
5
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);
class Test
{
// A Generic method example
static <T> void genericDisplay (T element)
{
System.out.println(element.getClass().getName() +
" = " + element);
}
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);
Output :
java.lang.Integer = 11
java.lang.String = HelloWorld
java.lang.Double = 1.0
6
Check your progress-1
1. What are generics? Explain with example?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
5.2.GENERIC
5.2.GENERIC CLASSES
A generic class declaration looks like a non-generic class declaration, except that the class
name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or
more type parameters separated by commas. These classes are known as parameterized
classes or parameterized types because they accept one or more parameters.
Like C++, we use <> to specify parameter types in generic class creation. To create objects
of generic class, we use following syntax.
Example:
Following example illustrates how we can define a generic class:
public class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
7
}
}
OUTPUT:
Integer Value: 10
String Value: Hello World
Another example:
OUTPUT:
15
OOP in JAVA
8
5.3.SUMMARY
5.3.SUMMARY
A generic function takes arguments, performs a series of operations, and perhaps returns
useful values. An ordinary function has a single body of code that is always executed when
the function is called. A generic function has a set of bodies of code of which a subset is
selected for execution. The selected bodies of code and the manner of their combination are
determined by the classes or identities of one or more of the arguments to the generic
function and by its method combination type. Ordinary functions and generic functions are
called with identical function-call syntax.
Generic methods are those methods that are written with a single method declaration and
can be called with arguments of different types. The compiler will ensure the correctness of
whichever type is used. These are some properties of generic methods:
• Generic methods have type parameter (the diamond operator enclosing the type)
before the return type of the method declaration
• Type parameters can be bounded (bounds are explained later in the article)
• Generic methods can have different type parameters separated by commas in the
method signature
• Method body for a generic method is just like a normal method
Java generics is a powerful addition to the Java language as it makes the programmer’s job
easier and less error prone. Generics enforce type correctness at compile time and most
importantly, enables implementing generic algorithms without causing any extra overhead
to our applications.
9
5.4. MODEL EXAMINATION QUESTIONS.
QUESTIONS.
I: True/False questions
1. A generic type is a primitive.
2. Java generic has an advantage of making the programmer’s job easier and less
error prone.
3. It is possible to have interfaces with generic class types.
4. All generic method declarations have a type parameter section delimited by
angle brackets<>.
5. We can write a single generic method declaration that can be called with
arguments of different types.
10