Creating a Type-Specific List [5.0]
Generics can be used to create a list that will hold only objects of a
certain type. This example creates a list of Integer objects.
A list 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.
Note that although null is not a subclass of any type, if the
collection supports null values, it can be added to the type-specific
collection.
A value retrieved from a type-specific list
does not need to be casted.
In this example, a URL value is retrieved and used without an
explicit cast.
List<Integer> intlist = new ArrayList<Integer>();
intlist.add(new Integer(123));
// intlist.add("hello"); <- Syntax error
List<Number> numlist = new ArrayList<Number>();
numlist.add(new Integer(123));
numlist.add(new Float(123));
intlist.add(null);
List<URL> urlList = new ArrayList<URL>();
try {
urlList.add(new URL("http://javaalmanac.com"));
} catch (MalformedURLException e) {
}
String s = urlList.get(0).getHost();
really simple and good examples. i would be happy to see further examples here. thanks
it's good one