Generics
Type Parameter Naming Conventions
Type Casting
public class Box
{
	private Object obj;

	public Box(Object o)
	{
		obj = o;
	}

	public Object getObj()
	{
		return obj;
	}
}
			
public class G
{
	public static void main(String args[])
	{
		Box b = new Box("Hello World!");

		String a = (String)b.getObj();//type casting

		System.out.println(a.toLowerCase());
	}
}
			
Generic Class
public class Box<T>
{
	private T obj;

	public Box(T o)
	{
		obj = o;
	}

	public T getObj()
	{
		return obj;
	}
}
			
public class G
{
	public static void main(String args[])
	{
		Box<String> b = new Box<String>("Hello World!");

		String a = b.getObj();

		System.out.println(a.toLowerCase());
	}
}
			
Diamond
public class G
{
	public static void main(String args[])
	{
		Box<String> b = new Box<>("Hello World!");

		String a = b.getObj();

		System.out.println(a.toLowerCase());
	}
}
			
Multiple Types
public class Pair<T, S>
{
	private T name;
	private S age;

	public Pair(T n, S a)
	{
		name = n;
		age = a;
	}

	public T getName()
	{
		return name;
	}

	public S getAge()
	{
		return age;
	}
}
			
public class G
{
	public static void main(String args[])
	{
		Pair<String, Integer> p = new Pair<String, Integer>("Lin", 37);

		System.out.println(p.getName()+": "+p.getAge());
	}
}
			
Generic Method
public class G
{
	public static <T, S> boolean compare(Pair<T, S> p1, Pair<T, S> p2)
	{
		if(p1.getName().equals(p2.getName()) && p1.getAge().equals(p2.getAge()))
			return true;
		else
			return false;
	}

	public static void main(String args[])
	{
		Pair<String, Integer> p = new Pair<String, Integer>("Lin", 37);
		Pair<String, Integer> p2 = new Pair<String, Integer>("Lin", 38);

		Systemystem.out.println(G.<String, Integer>compare(p, p2));
		System.out.println(compare(p, p2));//type interface
	}
}
			
Bounded Type Parameters
public class Box<T extends Number>
{
	private T obj;

	public Box(T o)
	{
		obj = o;
	}

	public T getObj()
	{
		return obj;
	}
}
			
public class G
{
	public static void main(String args[])
	{
		Box<Integer> b = new Box<Integer>(100);
		//Box<String> b = new Box<String>("Hello World!");//compile erro

		System.out.println(b.getObj());
	}
}
			
Wildcard
import java.util.*;

public class G
{
	public static double sumOfList(List<? extends Number> list) {
		double s = 0.0;
	    	for (Number n : list)
			s += n.doubleValue();
	    	return s;
	}

	public static void main(String args[])
	{
		List<Integer> li = Arrays.asList(1, 2, 3);
		System.out.println("sum = " + sumOfList(li));
	}
}
			
Generic Array
import java.util.*;

public class temp
{
	public static void main(String args[])
	{
		List[] l2 = new List<?>[2];

		l2[0] = new ArrayList<Integer>();
		l2[1] = new ArrayList<Integer>();

		l2[0].add(1);
		l2[0].add(2);

		Object [] array = l2[0].toArray();

		for(Object e : array)
			System.out.println(e);
	}
}
			
Reference
  • Generic Array
  • Oracle Tutorial
  • Geekforgeek