Java Generics

Published: September 28, 2015

In Resources.


Generics in Java allow you to define class or interface which operates on several different object types - depending on class type declaration.

Sample class:

public class Pair<T, U> {
  private T first;
  private U second;

  public Pair() { first = null; second = null; }

  public Pair(T firstValue, U secondValue) {
    first_ = firstValue;
    second_ = secondValue;

  public String toString() {
    return "(" + first + ", " + second + ")";

// usage:
Pair<String, Integer> pair = new Pair<>("Mach", 3);
System.out.println("Pair: " + pair);

Longer version:

Differences between Java generics and C++ templates

Java generics is very different from C++ templates:


  • in Java you can easy specify requirements for parent or derived classes


  • you cannot use primitive types as generic type argument
  • type information is erased during program execution (look for "type erasure" and "reflection" below)
  • you cannot work with numbers in generic (universal) way - because of type erasure and lack of methods in base class (Number) - see N.1
  • you cannot use directly "new" on generic type or array of this type


  • for single type mentioning instead of using auto you use diamond operator

Introductory tutorials

Corner cases

Using reflection

Producer Extends Consumer Super - PECS rule

This rule comes from great book "Effective Java" by Joshua Bloch (Item 28) and describes in short form when to use "extends" and "super" bounds in generic types.

See tutorials:



  • "Java Generics and Collections" - Maurice Naftalin / Philip Wadler, 2006

See also