You are on page 1of 6

Before Generics: What is Generic Programming?

In the simplest definition, generic programming is a style of

computer programming in which algorithms are written in terms of to-bespecified-later types that are then instantiated when needed for specific
types provided as parameters

Java Generics
Why Generics?
Generics forces the developer to add only specific objects to the collection
to avoid runtime exception while casting.
For example:
List list = new ArrayList(); //Before generics
list.add(test); //adding data of String type to arraylist
list.add(new Dog()); //new method
list.add(Demo);//adding string type data to arraylist

Display(List list){
String str1=(String)list.get(0);
String str2=(String)list.get(1); //very Dangerous ClassCastException-Runtime exception
String str3=(String)list.get(2);
List<String > list = new ArrayList<String>();
list.add(new Dog());

/*Compiler error ->Only String is allowed ->

Generics help us to find bugs during coding*/

What are Generics?

Generics are a facility of generic programming that were added to the Java
programming language in 2004 within J2SE 5.0. They allow "a type or
method to operate on objects of various types while providing compiletime type safety. " This feature specifies the type of objects stored in a Java
Collection. In the year 1998, Philip Wadler created Generic Java, an
extension to the Java language to support generic types. Generic Java was
incorporated, with the addition of wildcards, into the official Java
language version J2SE 5.0.
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.

Eg 1: Simple Program for understanding Generics

import java.util.ArrayList;
public class Generics {
public static void main(String[] args) {
ArrayList<String> nums = new ArrayList<String>();

for(String s : nums){
int i = nums.indexOf(s);
System.out.println(i+" = "+s);

Eg 2: Program for Array printing using Generic method

public class GenericMethodTest{
// generic method printArray
public static < E > void printArray( E[] inputArray ) { // <> - Generic
// Display array elements
for ( E element : inputArray ){
System.out.printf( "%s ", element );
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' };
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
Output for above Program:

Array integerArray contains:

1 2 3 4 5
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:

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.

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

The above Program produces the following Output:

Integer Value :10

String Value :Hello World

Five bullet points about Java Generics:

Generics are implemented using Type Erasure

Generics does not support sub-typing

You can't create Generic Arrays

Use of wildcards with extends or super to increase API


Use of Multiple Bounds