What Are Generics? A Simple Generics Example : Generics Basics « Generics « Java Tutorial






The term generics means parameterized types. (Java 2 V5.0 (Tiger) New Features by Herbert Schildt )

  1. T is a type parameter that will be replaced by a real type.
  2. T is the name of a type parameter.
  3. This name is used as a placeholder for the actual type that will be passed to Gen when an object is created.
class GenericClass<T> {
  T ob;

  GenericClass(T o) {
    ob = o;
  }

  T getob() {
    return ob;
  }

  void showType() {
    System.out.println("Type of T is " + ob.getClass().getName());
  }
}

public class MainClass {
  public static void main(String args[]) {
    // Create a Gen reference for Integers.
    GenericClass<Integer> iOb = new GenericClass<Integer>(88);
    iOb.showType();

    // no cast is needed.
    int v = iOb.getob();
    System.out.println("value: " + v);

    // Create a Gen object for Strings.
    GenericClass<String> strOb = new GenericClass<String>("Generics Test");
    strOb.showType();

    String str = strOb.getob();
    System.out.println("value: " + str);
  }
}
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test








12.1.Generics Basics
12.1.1.Life without Generics
12.1.2.What Are Generics? A Simple Generics Example
12.1.3.Generics Work Only with Objects
12.1.4.A Generic Class with Two Type Parameters
12.1.5.Introducing Generic Types
12.1.6.Working with generic List
12.1.7.Nested generic type
12.1.8.A generic type can accept more than one type variables.
12.1.9.Raw Types and Legacy Code