Generics

index
INTERMEDIATE

Generics, also known as parameterized types, are classes which take as parameters one or more object types. (Primitive types may not be used.) Many Sun-supplied classes have been "genericized" in Java 5. For compatibility with older programs, genericized classes may still be used without type parameters, though this will result in warning messages from the compiler.

Genericized types provide you with more type safety. For example, before generics you could put any kind of object into an ArrayList; with generics you can specify that only certain types of objects can be put into an ArrayList. As an added bonus, when you retrieve an object from a genericized ArrayList, you no longer have to cast it to the correct type.

Using a genericized class

To declare a variable of a genericized class, use the following syntax:

ClassName<type, ..., type> variable;
    or
ClassName<type, ..., type> variable =
    new ClassName<type, ..., type>(parameters);

For example,

ArrayList<String> words = new ArrayList<String>();

HashMap<String, Person> people = new HashMap<String, Person>();

The genericized type name can be used wherever an "ordinary" type name can be used, such as in the declaration of a method. For example,

int find(String target, ArrayList<String> words) { ... }

ArrayList<String> longWords = getLongWords(ArrayList<String> words) { ... }
ADVANCED

Defining a genericized class

To define a genericized class, use the syntax:

class ClassName<typeVariable, ..., typeVariable> { ... }

Within the class definition, the typeVariables can be used almost any place type names can be used.

Here's an example of a genericized class:

import java.util.*;
 
public class Box<T> {
    private List<T> contents;
 
    public Box() {
        contents = new ArrayList<T>();
    }
 
    public void add(T thing) { contents.add(thing); }
 
    public T grab() {
        if (contents.size() > 0) return contents.remove(0);
        else return null;
    }
}

You can use a type variable, such as T above, almost any place you can use the name of a type. Here are the exceptions: