Saturday, September 17, 2011

Generics in Java is one of important feature added in Java 5 along with Enum, autoboxing and varargs , to provide compile time type-safety. Generics is also considered to be one of tough concept to understand in Java and somewhat it’s true as well. I have read many articles on generics in Java, some of them are quite good and detailed but I still felt that those are either too much technical or exhaustively detailed, so I thought to write a simple yet informative article on Java generics to give a head start to beginners without bothering there head too much. In this Java generics tutorial I will cover How Generics works in Java, Mysterious wild-cards in Generics and some important points about Generic in Java. I will try explaining generics concept in simple words and simple examples. On a different note, If you like to learn new concepts by following books then you should check Java Generics and Collection, one of the best book on Generics, which covers from basics to best practices.

Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at runtime which was quite frequent error in Java code, for those who doesn’t know what is type-safety at compile time, it’s just a check by compiler that correct Type is used in correct place and there should not be any ClassCastException. For example HashSet of String will only contain String object and if you try to put Integer or any other object, compiler will complain. Before Java 5 same code will pass compile time check but will fail at runtime which is worse. Generics allows Java programmer to write more robust and type-safe code. In my opinion generics in Java is much overdue feature given popularity of Collection framework in java and its limitation around handling type-safety. Though Generics may look very complex because of its mysterious angle bracketing <> and various wild cards on Java generics, but once you understand the purpose of Generics in Java or Why Generics is introduced in Java you will be very comfortable and love writing code using Generics. If you are beginner and not familiar with Generics I strongly suggest you put some time and understand the Generics and stop writing collection classes without Generics. It not only saves you from mischievous ClassCastException but also gives you more readability and deterministic behavior from code. In this Java Generics tutorial we will see some important points around Generics and Java and will revise some stuff you may know.

How Generics works in Java

This is a popular Java Generics interview question which comes in my mind little late, It didn't come when I first know about generics in Java but a while later, nevertheless I find it quite useful to know about how generics works in java behind the scene. The buzzing keyword is "Type Erasure", you guessed it right it’s the same thing we used to in our schools for erasing our mistakes in writing or drawing :). Same thing is done by Java compiler, when it sees code written using Generics it completely erases that code and covert it into raw type i.e. code without Generics. All type related information is removed during erasing. So your ArrayList<Gold> becomes plain old ArrayList prior to JDK 1.5, formal type parameters e.g. <K, V> or <E> gets replaced by either Object or Super Class of the Type. Also when the translated code is not type correct compiler inserts a type casting operator. This all done behind the scene so you don't need to worry about what important to us is that Java compiler guarantees type-safety and flag any type-safety relate error during compilation. In short Generics in Java is syntactic sugar and doesn’t store any type related information at runtime. All type related information is erased by Type Erasure, this was the main requirement while developing Generics feature in order to reuse all Java code written without Generics.

Rules and Examples of Generics in Java

Let’s see some rule of using Generics in Java on Collections, Type safe class and type safe methods with simple examples:

1) Parametrized type like Set<T> is subtype of raw type Set and you can assign Set<T> to Set, following code is legal in Java:

4)Parametrized Type also follow Inheritance at main Type level means both HashSet<String> and LinkedHashSet<String> are sub types of Set<String> and legal by compiler as shown in following Generics example in Java :

6)Set<? super TreeMap> is another example of bounded wildcards, which will store instances of TreeMap or super class of TreeMap. See following Generics example in Java :

Set<?superTreeMap> setOfAllSuperTypeOfTreeMap = newLinkedHashSet<TreeMap>();//legal because TreeMap is superType of itself

setOfAllSuperTypeOfTreeMap = newHashSet<SortedMap>();//legal because SorteMap is super class of TreeMap
setOfAllSuperTypeOfTreeMap = newLinkedHashSet<Map>();//legal since Map is super type of TreeMap

7) You can not use Generics in .class token, parametrized types like List<String> are not allow along with .class literal.

List.class//legalList<String>.class//illegal

This is the one place where you need to use Raw type instead of parametrized type in Java.

8) If you are writing Generics method than you need to declare type parameters in method signature between method modifiers and return type as shown in below Java Generics example :

publicstatic<T> T identical(T source){return source;}

failing to declare <T> will result in compile time error. to know more read How to write Generics method in Java

Generics notations and naming Convention

One of the reason Generics looks tough is due to non familiarity of various Generics terms and naming conventions. Once you know meaning and name of various terms in generics you will feel more comfortable with Generics in Java. Following are some of the frequently used terms in Generics:

Generic Term

Meaning

Set<E>

Generic Type , E is called formal parameter

Set<Integer>

Parametrized type , Integer is actual parameter here

<T extends Comparable>

Bounded type parameter

<T super Comparable>

Bounded type parameter

Set<?>

Unbounded wildcard

<? extends T>

Bounded wildcard type

<? Super T>

Bounded wildcards

Set

Raw type

<T extends Comparable<T>>

Recursive type bound

T – used to denote type

E – used to denote element

K – keys

V - values

N – for numbers

Array and Generics in Java

1) Arrays doesn't support Generics in Java so you can not create Arrays like T[] which makes gentrifying an existing class hard if you are using arrays. Though there are work around which requires a cast from Object[] to T[] which comes with risk of unchecked cast and warning. For this reason it's better to use Collections classes like ArrayList and HashMap over array. by the way those classes are also implemented on top of array in Java but JDK handles there type-safety by effectively using generics. here is an example of casting Object array to generic array in Java :

Casting code may generate warning about "unsafe cast" which can be suppressed by using annotation @SuppressWarnings("unchecked") with proper comment that why it will not compromise type-safety. This is also one of the Java Generics best practices suggested in all time classic book Effective Java by Joshua Bloch.

Generics in Java – Benefits and advantages

Generics adds lot of value into Java programming language, here are some of important benefits of using Generics in Java:

Type-safety

Most important advantage of Generics in Java is type-safety. Collections prior to JDK1.5 are not type-safe because they accept Object type argument which allows them to catch all type of objects instead of only required type of object. For example if you want to create an ArrayList of Stocks and you don't want that ArrayList also contain any other asset class you can use generics feature of java to create a type-safe collection. Here is an example of using Generics to create a type-safe ArrayList

With Generics compiler ensures that correct types are added into Java collection classes and no cast is required while retrieving element, So there is no risk of ClassCastException at runtime.

Generics in Java – Important points

Some important feature of Generics in Java worth remembering:

1) One limitation of Generics in Java is that it can not be applied to primitive type, for example you can not create pass primitives in angle bracket that will result in compilation error, for Example ArrayList<int> will result in compilation error, This is little counter-intuitive that why auto-boxing can not covert int to Integer. If you try same thing with our Generic Holder class you will get following compilation error:

2) Generics in Java eliminates ClassCastException while retrieving objects from Collection, Remember prior to JDK1.5 if you retrieve objects from Collection you first check for a particular type and then cast, no need to do it now.

3) A parametrized class in Java use formal type parameters to retrieve Type information when instance of parametrized class gets created. In below example of generics class in Java <K,V> are formal parameters.

interface Cache <K,V>{public V get();public V put(K key, V value);}

As per convention followed on Generics version of Java Collection package we can use <K,V> for key and value type parameters.

4) Generics are often related to Templates in C++, though Unlike "Template" in C++, which creates a new type for each specific parametrized type, parametrized class in Java is only compiled once and more importantly there is just one single class file which is used to create instances for all the specific types.

5) Generics in Java can not only apply on Java Classes but also on methods, so you can write your own generics methods in Java as shown on Rules of Generics in Java section, here is another example of parametrized method from Java collection package.

boolean add(E o){}

Here E will be replaced by actual type parameter when this method will get called.

6) Another worth noting feature of Generics in Java is its ability to limit Types parameters, for example in parametric declaration of Holder<T extends Closeable>, type parameter list <T extends Closeable> requires that actual parameter T must be either Closeable or sub-type of Closeable. This is called bounded type parameters in Generics . this kind of declaration allows you to call method of Closeable interface without casting type parameter into Closeable. read more about these type parameters in bounded and unbounded wildcards in Generics.

7) Type inference : Generics in Java does not support type inference while calling constructor or creating instance of Generic Types until JDK7, In Java 7 along with Automatic resource management and String in Switch also added a new operator called Diamond operator and denoted by <> which facilitate type inference while creating instance of Generics classes. this helps to reduce redundancy and clutter. here is an example of Diamond operator in Java7 code:

On related note Generics in Java supports type inference while calling Generic methods and this feature can be used to create in combination of Factory design pattern in Java to create static factory method corresponding to each constructors. for example

so we can replace call to constructor with this static factory method as shown below :

HashMap<String, Set<Integer>> contacts = newContacts();

this can be used as alternative to diamond operator in Java 5 or 6.

Section for absolute beginners on Generics in Java

If you are absolute beginners in generics those angle bracket "<>" may look strange and unreadable to you. Though is not a complete tutorial on Java Generics and I would suggest you to read Java docs on Generics I will try to give at least some basic idea of generics in Java to get you going. Remember Generics in java are introduced to enforce type-safety especially on collection classes of java which holds type of Object e.g. ArrayList, HashMap.

Type-safety means compiler will verify type of class during compile time and throw compiler error if it found improper type. For example if an ArrayList of Gold contains Silver compiler will throw error.

ArrayList<Gold> goldList = new ArrayList<Gold>();

<Gold> tells compiler that this ArrayList must contain only Gold.

Generics can also be used to write parametric classes like Cache<Key, Value> on which type of Key and Value can be specified while creating objects.

Parameters used to write code is called "formal type parameters" and parameters which passed while creating instance of a generic class in java is called "actual type parameters". For example in our generic cache (below) <K, V> are formal parameter while new LRUCache<String, Integer>() will be actual parameters.

Generics wild cards Example in Java

There are generally two kinds of wild-cards in Generics, Bounded and unbounded. Bounded wildcards can be written in two ways to denote upper bound and lower bound. <?> is called unbounded wildcards because it can accept any Type while <? extends T> and <? super T> are bounded wildcards. To know more about them see my post Bounded vs Unbounded wildcards in Generics . Now let’s see example of different wildcards in Generics:

<?>

"?" denotes any unknown type, It can represent any Type at in code for. Use this wild card if you are not sure about Type. for example if you want to have a ArrayList which can work with any type than declare it as "ArrayList<?> unknownList" and it can be assigned to any type of ArrayList as shown in following example of generics in Java:

After learning about how to use Generics in Java for writing type-safe classes, methods and collection, its worth noting to remember best practices related to Generics coding:

1) Avoid using Raw types for new code. Always use Generics and write parametrized classes and method to get full benefit of compiler checking.

2) Prefer Collection classes over Array in your parametrized class because Generics and Arrays are completely different to each other, Array hold type information at runtime unlike Generics whose type information is erased by type-erasure during run time.

4) Use @SuppressedWarning("unchecked") at as narrow scope as possible like instead of annotating a method, just annotate a line. Also document rational of why this cast is type-safe as code comments.

5) Convert your raw type classes into type-safe parametric class using Generics in Java as and when time allows, that will make code more robust.

Generic in Java is very vast topic and there are lot more to be learn to get expertise on Java Generics. I hope this will serve you a good starting point in terms of reading code written using Generics and get over with complex wild card of Generics. Java Generics is one of the beautiful feature and once you used to it you won’t write classes or methods without generics. Initially Generics looks tough and complex but its worth learning given type-safety benefits it provides. Two things I would suggest you to do as beginner first write collection code always using Generics and write some type-safe classes which can accept parameter e.g. type-safe cache Cache<Key, Value>

Further Reading
on Java Generics

Generics is a complex topic and
effective use of Generics is not easy to learn, but following books has done
great job on explaining power of Generics and how to take advantage of that,
while writing parameterized interface and classes. This books not only contains
good details of Generics and it’s benefit but also best practices of using
Generics in Java.

20 comments
:

Anonymous
said...

Great tutorial on Generics, thanks a lot. I was looking for something which can teach me basics of Generics in Java and at least allow me to understand generics code written in Java and this java generics tutorial is exactly what I was looking.

Thanks for your Java Generics Tutorial man, you have make me to understand those cryptic angle brackets. I agree Generics in Java is little difficult topic and get a while to understand but tutorials like this are very helpful.

I have small note to point 5: provided you mean java.util.Collection and its subtypes, boolean add(E o) is NOT a generic method. It's simply a method of generic class. Generic methods have their own formal type parameter which is completely independent on class itself. In most often cases generic method are static or their class is not generic, but sensible exceptions exist, see http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Ordering.html for example. Tomas Zalusky

I agree Generics in Java is a convoluted concept but it makes coding quite easy. What makes Generics difficult it steep learning curve but once you get familiar with basics of Generics in Java , it would be more intuitive. Thanks for such a nice tutorial on Generics. Does anything changes related to Generics in Java from Java5 to Java6 and JDK7 onwards ?

Generics in Java is way too complex specially for common Java developers. Generic tutorial like this will help with certain extent but to get mastery on Generics in Java you will eventually need to write lots of Generic classes, interfaces and code. no substitute for that.

I agree with Billy, just reading theory on Generics or Java is not enough, you gotta write down generic classes, method and generic collection code. you got to understand concept of type-erasure and how it achieves type-safety at compile time for generics java code also.

How does Generics works in Java, I was looking answer of this questions from long time. Can you suggest where in Java API I can see internal working of Generics, How Type erasure actually works, In which language Generics type erasure are written, can we see the code before Generics and after Type erasing. Thanks to you for bringing key point like :

1) Generics type information is lost during runtime.2) Generics ensure type-safety during compile time etc.

I must say, one of the best Generics tutorial for Java, comprehensive and from basics to best practices. I was asked to explain How does Generics works internally in Java? didn't know about type erasure, but a quick read to this tutorial, gives me enough knowledge to answer such interview question. Thanks dude.

Can you tell me two reasons for using Generics in Java? I am coming from Java 1.4 and found learning Generics really hard, so before investing time and making my code changes, I would like to know What benefits Generics provides? What happens if you don't use Generics, as I am not using it currently and my code is perfectly fine.

Well, Generics in Java are not perfect. They're not reified, available at runtime, or specializable, and there are some weird restrictions on what you can do with generics. For example, you can't capture a lower bound into a variable, only into a wildcard, What I mean is you can not do C super T, only ? super T is permitted.