What are Java generics?

Ordinary classes and methods work with specific types: either primitives or class types. If you are writing code that might be used across more types, this rigidity can be overconstraining.


Java Generics are a language feature that allows for definition and use of generic types and methods. Generic types or methods differ from regular types and methods in that they have type parameters.


Examples of generic types can be found in the collection framework of the J2SE 5.0 platform libraries. A class like LinkedList<E> is a generic type. It has a type parameter E that represents the type of the elements stored in the list. Instead of just using a LinkedList, not saying anything about the type of elements the list contains, we can use a LinkedList<String> or a LinkedList<Integer> , thereby specifying that we mean a list of strings or integral values respectively.


Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters.


Point to remember :We can have an implementation of one generic class that can be instantiated for a variety of types.


For your better understanding execute each code provided in the examples!

package com.generics;

import java.util.*;

public class RandomList<T> {
	private ArrayList<T> storage = new ArrayList<T>();
	private Random rand = new Random(47);

	public void add(T item) {
		storage.add(item);
	}

	public T select() {
		return storage.get(rand.nextInt(storage.size()));
	}

	public static void main(String[] args) {
		RandomList<String>rs = new RandomList<String>();
		for (String s : ("The quick brown fox jumped over "
				+ "the lazy brown dog").split(" "))
			rs.add(s);
		for (int i = 0; i < 11; i++)
			System.out.print(rs.select() + " ");
	}
}


Why we should use Generics

Error detection during compilation

Using a parameterized type such as LinkedList<String>, instead of LinkedList, enables the compiler to perform more type checks and requires fewer dynamic casts at runtime.So errors will be detected earlier,in the sense that they are reported at compile-time by means of a compiler error message rather than at runtime by means of an exception. Consider the example of a LinkedList<String>.


The type LinkedList<String> expresses that the list is a homogenous list of elements of type String. Based on the stronger information the compiler performs type checks in order to ensure that a LinkedList<String> contains only strings as elements. Any attempt to add an alien element is rejected with a compiler error message.


Example (using a parameterized type):
			LinkedList<String> list = new LinkedList<String>();
			list.add("abc");       // fine
			list.add(new Date()); // error
			

Using a simple LinkedList,there is no knowledge and no guarantee regarding the type of the element retrieved.All retrieval methods return an Object reference, which must be cast down to the actual type of the element retrieved.

Same example (using a non-parameterized type):

			LinkedList list = new LinkedList();
			list.add("abc"); 
			String s = (String)list.get(0);  // cast required
		

The cast would fail at runtime with a ClassCastException in case the element retrieved is not of type String.
This type of runtime failure cannot happen with a parameterized list because the compiler already prevents insertion of an alien element into the sequence











Related Examples


Write a program to check if an input String is Palindrome or not?
Calculate the factorial of a given number using Java?
How to reverse a number in Java?
Write a program to convert from decimal to binary?
Producer Consumer Example in Thread
Write a program to reverse a String?








Receive Latest Java Examples in Your Email: