Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

/java/java-genericsPrevious             Next

Java Generics

Generics is a Java feature that was introduced with Java SE 5.0 . The feature of Generics in Java allows Applications to create classes and objects that can operate on any defined types.


The Motivation for Generics

The simplest way to think about Java generics is thinking about a sort of a syntactic sugar that might spare you some casting operation:
List<Apple> box = new ArrayList<Apple>();
Apple apple = box.get(0);
The previous code is self-speaking: box is a reference to a List of objects of type Apple. The get method returns an Apple instance and no casting is required. Without generics, this code would have been:
List box = new ArrayList();
Apple apple = (Apple)box.get(0);
Needless to say, the main advantage of generics is having the compiler keep track of types parameters, perform the type checks and the casting operations: the compiler guarantees that the casts will never fail.

Instead of relying on the programmer to keep track of object types and performing casts, which could lead to failures at runtime difficult to debug and solve, the compiler can now help the programmer enforce a greater number of type checks and detect more failures at compile time.


 The Generics Facility

The generics facility introduced the concept of type variable. A type variable, according to the Java Language Specification, is an unqualified identifier introduced by:
 Generic class declarations
 Generic interface declarations
 Generic method declarations
 Generic constructor declarations

 Generic classes and Interfaces
A class or an interface is generic if it has one or more type variable. Type variable are delimited by angle brackets and follow the class (or the interface) name:

interface HelloList extends Collection {
}
Many classes in the Java library, such as the entire Collections Framework, were modified to be generic. The List interface we've used in the first code snippet, for example, is now a generic class. In that snippet, box was a reference to a List object, an instance of a class implementing the List interface with one type variable: Apple. The type variable is the parameter that the compiler uses when automatically casting the result of the get method to an Apple reference.

In fact, the new generic signature or the get method of the interface List is:
T get(int index);
The method get returns indeed an object of type T, where T is the type variable specified in the List declaration.

 Generic Methods and Constructors
Pretty much the same way, methods and constructors can be generic if they declare one or more type variables.
public static T getFirst(List list) {
}
This method will accept a reference to a List and will return an object of type T.
Examples
You can take advantage of generics in both your own classes or the generic Java library classes. In the following code snippet, for example, we create an instance List of populates it with some data:
List str = new ArrayList();
str.add("Generics ");
str.add("World.");

If we tried to put some other kind of object into the List, the compiler would raise an error:

str.add(1); // won't compile

If we pass the List reference around, we're always guaranteed to retrieve a String object from it:
String myString = str.get(0);

Iterating
Many classes in the library, such as Iterator, have been enhanced and made generic. The iterator() method of the interface List now returns an Iterator that can be readily used without casting the objects it returns via its T next() method.
for (Iterator<String> iter = str.iterator(); iter.hasNext();) {
     String s = iter.next();
     System.out.print(s);
  }


Using foreach
The for each syntax takes advantage of generics, too. The previous code snippet could be written as:
List<String> str = new ArrayList<String>();
     str.add("Apple ");
     str.add("Mango ");
     for (String s: str) {
          System.out.print(s);
     }


Autoboxing and Autounboxing
The autoboxing/autounboxing features of the Java language are automatically used when dealing with generics, as shown in this code snippet:
List<Integer> ints = new ArrayList<Integer>();
     ints.add(100);
     ints.add(200);
     ints.add(300);
     int sum=0;
     for (int paa: ints) {
          sum += paa;
     }


/java/java-genericsPrevious             Next