|
| |
Here's the HashMap class, converted to using generics:
package examples;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapExample
{
public static void main(String[] args)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("Mary", "555-1234");
map.put("Frank", "555-5678");
map.put("Joe", "555-9012");
map.put("Sylvia", "555-3456");
map.put("Vanessa", "555-7890");
map.put("Frank", "555-0987"); // Duplicate
for (Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator(); iter.hasNext(); )
{
Map.Entry<String, String> entry = iter.next(); // Note NO required cast
String key = entry.getKey(); // Note NO required cast
String value = entry.getValue(); // Note NO required cast
System.out.println(key + ":" + value);
}
}
}
|
which outputs:
Vanessa:555-7890
Frank:555-0987
Sylvia:555-3456
Mary:555-1234
Joe:555-90
(This is not the same as the original -- it's in a different order -- but
since it's a HashMap, the order isn't guaranteed, anyway.)
|