Generics in Java

Generics refers to classes or interfaces which take another class or interface as a parameter. Typical example comes from collection type of classes like Lists, Hashtables...

Example 1:

List myList = new ArrayList();
myList.add(new Integer(100));
Integer i = (Integer) myList.get(0);

Example 2:

List<Integer> myList = new ArrayList<Integer>();
myList.add(new Integer(100));
Integer i = myList.get(0);

In example 1 we created myList object of List type, but we didn’t declare any type as parameter. In this case List is ready to accept Object instances. Also get(i) method returns an Object that is stored in the List and must therefore be casted to proper type (Integer in this case) first.

In example 2 we declared a List of Integers. In this case List will accept Integers only and get(i) method will return an Integer (no cast needed).

List is a generic interface which takes Integer type as a parameter.