View RSS Feed

Advanced Java

Different Java Generic Types

Rate this Entry
by , 02-18-2012 at 03:35 PM (640 Views)
By using Generics, implementation of Box class is done. It is shown in the given code

Java Code:
public class Box<T> {

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

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

    public T get() {
        return t;
    }
}
In given Box class replacement takes place with T, of all occurrences objects.

For referencing the given generic class in your code you shall be performing generic type invocation that makes the replacement of T, with a concrete value like an Integer:

Java Code:
Box<Integer> integerBox;
integerBox = new Box<Integer>();
Or entire statement could be place in 1 line, like:
Java Code:
Box<Integer> integerBox = new Box<Integer>();

Submit "Different Java Generic Types" to Facebook Submit "Different Java Generic Types" to Digg Submit "Different Java Generic Types" to del.icio.us Submit "Different Java Generic Types" to StumbleUpon Submit "Different Java Generic Types" to Google

Categories
Generics

Comments