Java Reference
In-Depth Information
element number in an array—it's a unique value used to access the data stored at a posi-
tion in the data structure.
You can put the key-mapped approach to work by using the Hashtable class or one of
the other classes that implement the Map interface. You learn about the Hashtable class
in the next section.
The Map interface defines a means of storing and retrieving information based on a key.
This is similar in some ways to the Vector class, in which elements are accessed through
an index, which is a specific type of key. However, keys in the Map interface can be just
about anything. You can create your own classes to use as the keys for accessing and
manipulating data in a dictionary. Figure 8.3 shows how keys map to data in a dictionary.
FIGURE 8.3
The organization of
a key-mapped data
structure.
Key0
Element0
Key1
Element1
Key2
Element2
Key3
Element3
The Map interface declares a variety of methods for working with the data stored in a dic-
tionary. Implementing classes have to implement all those methods to be truly useful.
The put and get methods are used to put objects in the dictionary and get them back.
Assuming that look is a class that implements the Map interface, the following code
shows how to use the put method to add elements:
Rectangle r1 = new Rectangle(0, 0, 5, 5);
look.put(“small”, r1);
Rectangle r2 = new Rectangle(0, 0, 15, 15);
look.put(“medium”, r2);
Rectangle r3 = new Rectangle(0, 0, 25, 25);
look.put(“large”, r3);
This code adds three Rectangle objects to the dictionary, using strings as the keys. To
get an element, use the get method and specify the appropriate key:
Rectangle r = (Rectangle)look.get(“medium”);
You also can remove an element with a key by using the remove() method:
look.remove(“large”);
 
Search WWH ::




Custom Search