Monday, June 4, 2012

JAVA: Generics

Courtesy : http://java.sun.com/docs/books/tutorial/java/generics

public class Box {

    private T t; // T stands for "Type"          

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

During compilation, all generic information will be removed entirely, leaving only Box.class on the filesystem.

A declaration of Box, for example, would generate an error on the second occurrence of T, but Box, however, would be allowed.

The most commonly used type parameter names are:
  • 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

No comments:

Post a Comment