Tutorials Books About
Java Generics

1 Java Generics Tutorial
2 Generic List in Java
3 Generic Set in Java
4 Generic Map in Java
5 Generic Classes in Java
6 Java Generic Methods
7 Java Generics - Class Objects as Type Literals
8 Java's Generic For Loop
9 Java Generics - Implementing the Iterable Interface
10 Java Generic's Wildcards

Java Generics Tutorial

The Java Generics features were added to the Java language from Java 5. Generics add a way to specify concrete types to general purpose classes and methods that operated on Object before. It sounds a bit abstract, so we will look at some examples using collections right away. Note: Generics can be used with other classes than the collection clasess, but it is easiest to show the basics using collections.

The List interface represents a list of Object instances. This means that we could put any object into a List. Here is an example:

List list = new ArrayList();

list.add(new Integer(2));
list.add("a String");

Because any object could be added, you would also have to cast any objects obtained from these objects. For instance:

Integer integer = (Integer) list.get(0);

String string   = (String) list.get(1);

Very often you only use a single type with a collection. For instance, you only keep String's or something else in the collection, and not mixed types like I did in the example above.

With Java's Generics features you can set the type of the collection to limit what kind of objects can be inserted into the collection. Additionally, you don't have to cast the values you obtain from the collection. Here is an example using Java's Generic's features:

List<String> strings = new ArrayList<String>();

strings.add("a String");

String aString = strings.get(0);

Nice, right?

Java 5 also got a new for-loop (also referred to as "for-each") which works well with generified collections. Here is an example:

List<String> strings = new ArrayList<String>();

//... add String instances to the strings list...

for(String aString : strings){

This for-each loop iterates through all String instances kept in the strings list. For each iteration, the next String instance is assigned to the aString variable. This for-loop is shorter than original while-loop where you would iterate the collections Iterator and call to obtain the next instance.

I'll write more about the new for-loops again later in this tutorial.

Java Generics for Other Types than Collections

It is of course possible to use Generics for other classes than the Java collections. You can generify your own classes too. I'll write more about that in later texts in this tutorial too.

Java Generics Tutorial - Table of Contents

Here is a list of the texts in this Java Generics tutorial:

Connect with me: Newsletter - Get all my free tips!