Java Template-Like Generics

Parameterized Types

See http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf for a detailed discussion.

Sample:

import java.util.*;
class TestTemplate
{

public static void main(String args[])
{
    LinkedList list = new LinkedList();

    list.add("b");
    list.add("f");
    //list.add(new Integer(5));
    list.add("c");
    System.out.println(list);

    LinkedList<String> stringList = new LinkedList<String>();
    stringList.add("b");
    stringList.add("f");
    // stringList.add(new Integer(5)); syntax error
    stringList.add("a");
    stringList.add("c");

    //LinkedList<int> intList = new LinkedList<int>(); syntax error

    System.out.println(stringList);

    // lets show iterators

    Iterator it1 = list.iterator();
    System.out.print("[");
    while (it1.hasNext())
    {
    String s = (String) it1.next(); // note cast necessary
    System.out.print(s+" ");
    }
    System.out.println("]");

    Iterator<String> it2 = stringList.iterator();
    System.out.print("[");   
    while (it2.hasNext())
    {
        String s = it2.next();
        System.out.print(s+" ");
    }
    System.out.println("]");

}

}

Advantage:

Type safety-- Programmer gets a compiler-error if try to add the wrong element-type to collection.