Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   3. Collections  >   3.3. The class HashMap

3.3. The class HashMap
Last updated: 31 January 2013.

This tutorial explains how to use the class HashMap.

The class HashMap implements the interface Map as an unsynchronized, resizable and unordered data structure that maps keys to values. To create a HashMap instance, you must provide two types: a type for the keys and a type for the values. The following sample creates a HashMap instance wherein keys are strings and values are instances of the class Integer:

Map<String, Integer> myHashMap = new HashMap<String, Integer>();

The next sample shows how to add mappings to the HashMap instance:

myHashMap.put("integer_1", new Integer(11));
myHashMap.put
("integer_2", new Integer(22));
myHashMap.put
("integer_3", new Integer(33));

To get a value that is mapped to a given key, you have to call the method get(Object key). For example, the sample shown below iterates over the keys and prints to the standard output the value to which each key is mapped:

for(String key : myHashMap.keySet())
   
System.out.println(myHashMap.get(key));

You can also iterate over the values by calling the method values like this:

for(Integer i : myHashMap.values())
   
System.out.println(i);

The class HashMap provides other useful methods such as contains(Object key), isEmpty, remove(Object key), clear and size. For further details about these methods, please refer to the Java API documentation.


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   3. Collections  >   3.3. The class HashMap
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   4. Networking

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7