A generic class, interface or method in Java is parameterized by one or more types. Generics in Java allow one implementation of a collection or algorithm to be reused with different reference types while checking the allowed values and results statically. For example:
Vector<String> names = new Vector<String>();
names.add("Ada");
String first = names.get(0);

class Box<T> {
    private T value;
    public void put(T x) { value = x; }
    public T get() { return value; }
}
The type parameter is declared inside angle brackets, as in Box<T>, and supplied as a type argument, as in Box<String>. A generic method places its parameter list before its return type, for example static <T> T identity(T x). Bounds such as <T extends Number> restrict type arguments, and wildcards such as ? extends Number or ? super Integer describe restricted views. Primitive values require wrapper types such as Integer rather than a type argument int. Generics provide reusable code with compile-time checking of element types.

Articles by others on the same topic (0)

There are currently no matching articles.