Saturday, 25 September 2010

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.

Map<Integer, String> map = new HashMap<Integer, String>(); 
map.put(1, "first"); 
map.put(2, "second"); 
// map.put(1, 2); <- Syntax error 
 
 
 
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.

Map<Number, String> numMap = new HashMap<Number, String>(); 
numMap.put(.5, "half"); 
numMap.put(1, "first"); 
 
 
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.

map.put(null, null); 
 
 
 
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<String, URL> urlMap = new HashMap<String, URL>(); 
try { 
            urlMap.put("java", new URL("http://java.com")); 
} catch (MalformedURLException e) { } 
String s = urlMap.get("java").getHost();

No comments:

Post a Comment