Creating a Mapped Collection


HashMap map = new HashMap(); map.put(key1, obj1); map.put(key2, obj2); map.get(key3, obj3);



In this phrase, we use a HashMap to create a mapped collection of objects. The HashMap has a put() method that accepts two parameters. The first parameter is a key value, and the second parameter is the object you want to store in the map. So, in this phrase, we are storing three objectsobj1, obj2, and obj3indexed by keyskey1, key2, and key3, respectively. The HashMap class is one of the most commonly used Java classes. In a HashMap, the objects put into a map should all be of the same class type. So if obj1 is a String object, then obj2 and obj3 should also be String objects.

To retrieve the objects that you put into the collection, you use the get() method of the HashMap. The get() method takes a single parameter, which is the key of the element you want to retrieve. If the element is found, it will be returned as a generic Object, so you would want to cast it to the type you are expecting. If the element you are trying to retrieve does not exist, a null value is returned.

Note

JDK 1.5 introduces a new language feature called Generics which would allow you to retrieve items from a HashMap without having to do any casting. Sun makes available an excellent article on using Generics at this site: http://java.sun.com/developer/technicalArticles/J2SE/generics/index.html


It is important that objects you are using as key values in a HashMap implement the equals() and hashCode() methods. These methods are used by the HashMap implementation to find elements in the map. If an object used as a key value does not have these methods implemented, key objects will be matched by their identity only, meaning that to find a matching key, you'd have to pass in the identical object instance when trying to retrieve an object. This is usually not what you want.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net