Java Generics

Published: September 28, 2015

In Resources.

Overview

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: Pair.java

Differences between Java generics and C++ templates

Java generics is very different from C++ templates:

Positives:

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

Negatives:

  • 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

Neutral:

  • 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:

Solutions

Books

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

See also

Share

follow