3 min read

Java Generics

Background

Generics are a Java programming construct that allow you to use types as parameters when you define classes, methods, and interfaces. This provides a way for you to re-use the same code with different inputs.

There are several benefits to using generics:

This code snippet without generics requires casting:

Dog myDog = new Dog(); List list = new ArrayList(); list.add(myDog); Dog d = (Dog) list.get(0); // Casting required here because list.get(0) returns an Object, not a Dog.

This code snippet, rewritten to use generics, does not require casting:

Dog myDog = new Dog(); List list = new ArrayList(); list.add(myDog); Dog d = list.get(0); // No casting necessary!

This also adds type safety by preventing illegal objects from being stored in the array:

Dog myDog = new Dog(); Cat badCat = new Cat(); List list = new ArrayList(); list.add(badCat); // This actually won’t compile because of this line. Can’t add a Cat to a Dog array.

Usage

Most of the time, the code you will write that deals with generics will be collection-related code. The way that you will use generics will be primarily in one of three ways:

Creating instances of generified classes:

new ArrayList() Declaring variables of generic types: List dogList = new ArrayList(); Declaring and invoking methods that take generic types: void foo(List list){ // Method stuff here } x.foo(dogList); // Invoking the method

Understanding the Documentation

The Java convention is to use “E” (for “element”) as the stand-in for the type of element a collection class should accept.

For example:

public class ArrayList extends AbstractList implements List

So, when implementing ArrayList, E becomes a Dog object.

In generics, “extends” means “extends” OR “implements.”

public static void sort<List list>

Normally, in Java, “extends” refers to class inheritance, where “implements” refers to interfaces. When dealing with generics, however, “extends” refers to both of these. Interfaces and classes are treated the same way.

Sure, the Java engineers probably could have used a new keyword, like “is,” or something. But generally, whenever there is a chance to re-use an existing keyword, it is best to do that in order to lessen the risk of breaking existing code.

References:

http://docs.oracle.com/javase/tutorial/java/generics/why.html Head First Java, 2nd Edition (book)

← All posts