Generics

Generics are classes, interfaces, methods, or constructors that use special variables called type variables.

ArrayList is an example of a generic class.

 

Type Variables

These are special variables that can be assigned types (the variables we normally use can be called value variables, because they are assigned values).

Purpose is to be used to declare value variables.

Example:

type var; //if type is a type variable, var will be declared with that type

 

Generic Class Definitions

class Class<type>
{
     ...
}

This creates a class with a type variable named type.

Type variables are accessible within the body, like how normal variables are.

Example:

//box that holds contents of a type.
class Box<type>
{
     type contents;
     Box(type contents)
     {
          this.contents = contents;
     }
}

Variables assigned generic class objects are declared and instantiated with angle brackets, having types to be passed to the constructor. Example (try it):

Box<String> stringbox = new Box<String>(“string”);

 

Generic Method Definitions

<type, type2, ...> return-type method()
{
     ...
}

This defines a method with type variables type, type2, ….

To be able to pass types to the method, make parameters preceded by type variables and write those type variables inside angle brackets.

Example:

<type> boolean equals(type a, type b)
{
     return a == b;
}

Modifiers (like static, public, etc.) must go before the angle brackets.

 

Constraining type variables

<type extends another-type>

This constrains what type can be to only types that extend another-type.

Example:

//test whether two Number values are identical.
<type extends Number> void test(type a, type b)
{
     System.out.println(a == b);
}

One can also use the keyword super to limit the type to be parent of another-type:

<type super another-type>

If you do not need to know nor use the passed type, you can change type to ? instead, for simplifying purposes:

<? super another-type> //cannot know ?

 

Naming conventions

I made my own names for type parameters in simplicity, like “type”. But these are the usual names people give to type parameters:

  • E – Element (used extensively by the Java Collections Framework)
  • K – Key
  • N – Number
  • T – Type
  • V – Value
  • S,U,V etc. – 2nd, 3rd, 4th types
Please like & share: