Studyon Minte9.com
Fundamentals (Docs)

Study

Generic Types



There's nothing particularly complex about this concept. In fact, it's quite similar to what you already know about 
variables in general. Just think of T as a special kind of variable, whose "value" will be whatever type you pass in.

	public class GenericTypeDemo {
	    
	    public static void main(String[] args) {
		
		Box2<Integer> a = new Box2<Integer>();
		
		// corect 
		...
		
		//incorect
		a.set("10"); // compiler error
		...
	    }
	}

	class Box2<T> {
	    
	    private T t;
	    
	    public void set(T t) {
		this.t = t;
	    }
	    public T get() {
		return t;
	    }
	}

Also note that a generic type may have multiple type parameters, but each parameter must be unique within its 
declaring class or interface. 
A declaration of Box<T,T>, for example, would generate an error on the second occurrence of T, but Box<T,U>, 
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


Generic Methods and Constructors

Type parameters can also be declared within method and constructor signatures to create generic methods and 
generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the 
method or constructor in which it's declared.

	public class GenericTypeDemo3<T> {
	    
	    private T t;
	    
	    public void set(T t) {
		this.t = t;
	    }
	    
	    public T get() {
		return t;
	    }
	    
	    public static void main(String[] args) {
		GenericTypeDemo3<Integer> box1 = new GenericTypeDemo3<Integer>();
		box1.set(new Integer(10));
		box1.inspect("some text");
	    }
	    
	    public <U> void inspect(U u) {
		System.out.println("T: " + t.getClass().getName()); // T: java.lang.Integer
		System.out.println("U: " + u.getClass().getName()); // U: java.lang.String
	    }
	}

Here we've added one generic method, named inspect, that defines one type parameter, named U. This method 
accepts an object and prints its type to standard output.

A more realistic use of generic methods might be something like the following, which defines a static method that
 stuffs references to a single item into multiple boxes:

	public static <U> void fillBoxes(U u, List<Box<U>> boxes) {
	    for (Box<U> box : boxes) {
		box.add(u);
	    }
	}


http://docs.oracle.com/javase/tutorial/java/generics/gentypes.html