0% found this document useful (0 votes)
10 views10 pages

Unit 51

This unit covers the concept of generics in Java, including generic methods and classes, and their implementation. It explains how generics provide compile-time type safety, allowing for the creation of methods and classes that can operate on different types without code duplication. The unit also includes examples and exercises to reinforce understanding of generics.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

Unit 51

This unit covers the concept of generics in Java, including generic methods and classes, and their implementation. It explains how generics provide compile-time type safety, allowing for the creation of methods and classes that can operate on different types without code duplication. The unit also includes examples and exercises to reinforce understanding of generics.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

UNIT 5:

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

5.0. AIMS AND OBJECTIVES

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:

• Understand what generics are and how to use them


• Implement generics in different programs
• Explain the difference between generic methods and generic classes

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:

public class Util {


public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}
public class Pair<K, V> {
private K key;
private V value;

2
public Pair(K key, V value) {
this.key = key;
this.value = value;
}

public void setKey(K key) { this.key = key; }


public void setValue(V value) { this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}

The complete syntax for invoking this method would be:

Pair<Integer, String> p1 = new Pair<>(1, "apple");


Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);

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:

Pair<Integer, String> p1 = new Pair<>(1, "apple");


Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);

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:

public class GenericMethodTest {

// generic method printArray

public static < E > void printArray( E[] inputArray ) {

// Display array elements

for(E element : inputArray) {

System.out.printf("%s ", element);

System.out.println();

public static void main(String args[]) {

// Create arrays of Integer, Double and Character

Integer[] intArray = { 1, 2, 3, 4, 5 };

Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };

Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

4
System.out.println("Array integerArray contains:");

printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");

printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");

printArray(charArray); // pass a Character array

This will produce the following result −

Output

Array integerArray contains:


1 2 3 4 5

Array doubleArray contains:


1.1 2.2 3.3 4.4

Array characterArray contains:


H E L L O

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);

// Calling generic method with String argument


genericDisplay("HelloWorld");

// Calling generic method with double argument


genericDisplay(1.0);
}
}
// 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
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);

// Calling generic method with String argument


genericDisplay("HelloWorld");

// Calling generic method with double argument


genericDisplay(1.0);
}
}

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.

// To create an instance of generic class


BaseType <Type> obj = new BaseType <Type>()

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:

// A Simple Java program to show working of user defined


// Generic classes

// We use < > to specify Parameter type


class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test <String> sObj =
new Test<String>("OOP in JAVA");
System.out.println(sObj.getObject());
}
}

OUTPUT:
15
OOP in JAVA

Check your progress-2


1. Explain the role of interfaces?
_________________________________________________________________________________________________
_________________________________________________________________________________________________

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.

II: Short Answer Questions

1. Explain the properties of generic methods?


2. Why do programmers need generics? Explain it with program?

10

You might also like