Creating a Type-Specific Map [5.0]
Generics can be used to create a map that will hold only objects of a
certain type. This example creates a map whose keys are Integer
objects and values are String objects.
A map declared to hold objects of a type T can also hold
objects that extend from T. In this example, a map is created to hold
Number objects as keys. 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 collection
does not need to be casted.
In this example, a URL value is retrieved and used without an
explicit cast.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "first");
map.put(2, "second");
// map.put(1, 2); <- Syntax error
Map<Number, String> numMap = new HashMap<Number, String>();
numMap.put(.5, "half");
numMap.put(1, "first");
map.put(null, null);
Map<String, URL> urlMap = new HashMap<String, URL>();
try {
urlMap.put("java", new URL("http://javaalmanac.com"));
} catch (MalformedURLException e) {
}
String s = urlMap.get("java").getHost();
Post a comment