The HashMap class implements the Map interface,
using a hash table:
Object
AbstractMap (implements Map)
HashMap
Because of the implementation, the entries in a HashMap have no
inherent ordering.
Here's an example of using the HashMap
class.
Note that in this example the
key is the person's name, and the value is the person's telephone number.
In general, the key and the associated value are not limited to strings:
package examples;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapExample
{
public static void main(String[] args)
{
HashMap map = new HashMap();
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 iter = map.entrySet().iterator(); iter.hasNext(); )
{
Map.Entry entry = (Map.Entry) iter.next(); // Note required cast
String key = (String) entry.getKey(); // Note required cast
String value = (String) entry.getValue(); // Note required cast
System.out.println(key + ":" + value);
}
}
}
|
which outputs:
Vanessa:555-7890
Joe:555-9012
Frank:555-0987
Mary:555-1234
Sylvia:555-3456
Note the similarities to the previous code. This is not
accidental. Again, it results from the consistent use of the appropriate
set of interfaces.
Also, we can tell from the output of the program that the final put has the effect of
replacing the value for
Frank that was entered earlier.
In particular, note the fact that a Map
does not have a direct
way of obtaining an iterator. Instead, it defines an interface, Entry,
nested within
the Map class. It also defines a method entrySet()
which returns a Set object (that is, an instance of a class that
implements Set) corresponding to the entries in the Map
You can then obtain an iterator from that Set
object. The
iterator returns Entry objects, from which you can obtain the key
and value.
|