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.
List<Integer> intlist = new ArrayList<Integer>(); intlist.add(new Integer(123)); // intlist.add("hello"); <- Syntax error
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.
List<Number> numlist = new ArrayList<Number>(); numlist.add(new Integer(123)); numlist.add(new Float(123));
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.
intlist.add(null);
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<URL> urlList = new ArrayList<URL>(); try { urlList.add(new URL("http://javaalmanac.com")); } catch (MalformedURLException e) { } String s = urlList.get(0).getHost();

Comments

29 Jan 2010 - 3:49am by Anonymous (not verified)

really simple and good examples. i would be happy to see further examples here. thanks

19 Feb 2010 - 8:13pm by Anonymous (not verified)

it's good one

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.