Jenkov.com
Tutorials About




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){
  System.out.println(aString);
}

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 Iterator.next() 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!
     



Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.
OK