Creating a Type-specific Collection [5.0]

Generics can be used to create a collection that will hold only objects of a certain type. This example creates a list of Integer objects.
List<Integer> intlist = new ArrayList<Integer>();

intlist.add(new Integer(123));
// intlist.add("hello");       <- Syntax error
null is a valid value that can be added to such collections.
A collection declared to hold objects of a type T can also hold objects that extend from T. In this example, a list is created to hold Number objects. Both Integer and Float are subclasses of Number.
List<Number> numlist = new ArrayList<Number>();

numlist.add(new Integer(123));
numlist.add(new Float(123));
A value retrieved from a type-specific collection does not need to be casted. In this example, a URL value is retrieved and used without an explicit cast.
List<URL> urlList = new ArrayList<URL>();
try {
    urlList.add(new URL(""));
} catch (MalformedURLException e) {
String s = urlList.get(0).getHost();