Java HashMap tutorials

Home arrow Java Tutorials arrow Java Essentials arrow Java HashMap tutorials
Java HashMap tutorials Print E-mail
User Rating: / 81
PoorBest 
Contributed by Howell   
Friday, 16 June 2006

Java HashMap Overview

A map is a way of storing data that minimizes the need for searching when you want to retrieve an object. Each object is associated with a key that is used to determine where to store the reference to the object, and both the key and the object are stored in the map.  

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

HashMap Supports the storage of any type of object in a hash table, sometimes called a map.

Creating a HashMap

All map classes implement the Map interface, so an object of any map class can be referenced using a variable of type Map.There are four constructors you can use to create a HashMap object:

The Hashing Process

The implementation of a map in the Java collections framework provided by the HashMap<> class sets
aside an array in which it will store key and object pairs. The index to this array is produced from the key object by using the hashcode for the object to compute an offset into the array for storing key/object pairs. By default, this uses the hashCode() method for the object that’s used as a key.

Constructor  Description
HashMap() 

 Creates a map with the capacity to store a default number of objects. The default capacity is 101 objects and the default load factor (more on the load factor below) is 0.75.

HashMap(int capacity)

 Creates a map with the capacity to store the number of objects you specify in the argument and a default load factor of 0.75.

HashMap(int capacity, float loadFactor)

Creates a hash table with the capacity and load factor that you specify.

HashMap(Map map)

To create a map using the default constructor,

HashMap theMap = new HashMap();

The capacity for a map is simply the number of key/object pairs it can store. The capacity increases automatically as necessary, but this is a relatively time consuming operation. The capacity value of the map is combined with the hash code for the key that you specify to compute the index that determines where an object and its key are to be stored. To make this computation produce a good distribution of index values, you should ideally use prime numbers for the capacity of a hash table when you specify it yourself. For example:

HashMap myMap = new HashMap(121);

The load factor is used to decide when to increase the size of the hash table. When the size of the table reaches a value which is the product of the load factor and the capacity, the capacity will be increased automatically to twice the old capacity plus 1 – the plus one ensuring it is at least odd, if not prime. The default load factor of 0.75 is a good compromise, but if you want to reduce it you could do so by using the third constructor:

HashMap aMap = new HashMap(121, 0.65f);  // 65% load factor 

Example of Creating a Java Hash Table
A hash table, or map, holds key/value pairs.
    // Create a hash table
    Map map = new HashMap();    // hash table
    map = new TreeMap();        // sorted map
   
    // Add key/value pairs to the map
    map.put("a", new Integer(1));
    map.put("b", new Integer(2));
    map.put("c", new Integer(3));
   
    // Get number of entries in map
    int size = map.size();        // 2
   
    // Adding an entry whose key exists in the map causes
    // the new value to replace the old value
    Object oldValue = map.put("a", new Integer(9));  // 1
   
    // Remove an entry from the map and return the value of the removed entry
    oldValue = map.remove("c");  // 3
   
    // Iterate over the keys in the map
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
    }
   
    // Iterate over the values in the map
    it = map.values().iterator();
    while (it.hasNext()) {
        // Get value
        Object value = it.next();
    }
Creating a Map That Retains Order-of-Insertion() (Java HashMap tutorial)

 Map map = new LinkedHashMap();
   
    // Add some elements
    map.put("1", "value1");
    map.put("2", "value2");
    map.put("3", "value3");
    map.put("2", "value4");
   
    // List the entries
    for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
        Object key = it.next();
        Object value = map.get(key);
    }

How to store a Map in a File (Java HashMap tutorial) 

import java.util.*;
import java.io.*;
class AddressBook implements Serializable {

  private File filename = new File("Addressbook.bin");
  private HashMap addressbook = new HashMap();.

  public AddressBook() {
    if(filename.exists())
    try {
      ObjectInputStream in = new ObjectInputStream(
      new FileInputStream(filename));
      addressbook = (HashMap)in.readObject();
      in.close();

    } catch(ClassNotFoundException e) {
      System.out.println(e);

    } catch(IOException e) {
      System.out.println(e);
    }
  }

  public void save() {
    try {
      System.out.println("Saving address book");
      ObjectOutputStream out = new ObjectOutputStream(
      new FileOutputStream(filename));
      out.writeObject(addressbook);
      out.close();

    } catch(IOException e) {
      System.out.println(e);
    }
  }

}


Storing, Retrieving, and Removing Objects of HashMap

 There have four methods which allow you easily to Store, retrieve, and remove objects in a HashMap

Method

Description

put(Object key, Object value)

Stores the object value in the map using the key specified by the first argument. value will displace any existing object associated with key. The ejected object will be returned as type Object. If no object is stored at that map location or the key was used to store null as an object, null is returned.

 

putAll(Map map)

Transfers all the key/object pairs from map to the current map, replacing any objects that exist with the same keys.

get(Object key)

Returns the object stored with the same key as the argument. If no object was stored with this key or null was stored as the object, null is returned.

remove(Object key)

Removes the entry associated with key if it exists, and returns the object as type Object. A null is returned if the entry does not exist, or if null was stored using key.

Processing all the Elements in a Map

 The Map interface provides three ways of obtaining a collection view of the contents of a map. You can obtain all the keys or all the key/object pairs from a Map object as an object of type Set. You can also get a Collection object that references all the objects in the map.

Method

Description

keySet()

Returns a Set object referencing the keys from the map..

entrySet()

Returns a Set object referencing the key/object pairs – each pair being an object of type Map.Entry.

values()

Returns a Collection object referencing the objects stored in the map.

An example

To get the set of all the keys in the map with the statement:

Set keys = myMap.keySet();

To get an iterator for this set of keys

Iterator it = keys.iterator();
while(it.hasNext())                            
System.out.println((KeyType)it.next());


 LinkedHashMap   (Java HashMap)

The LinkedHashMap and LinkedHashSet classes were added with JDK 1.4. LinkedHashMap is a child of HashMap, but unlike HashMap the elements are insertion ordered. The LinkedHashSet class is a child of HashSet and like HashSet the elements must be unique, but unlike HashSet, elements are insertion ordered.


Question about Java HashMap

What happens when you attempt to compile and run the following code?

 import java.util.*;
public class RapCollect {
    public static void main(String argv[]){
   HashMap hm = new HashMap();
        hm.put("one", new Integer(1));
        hm.put("two", new Integer(2));
        hm.put("three",new Integer(3));
        Set set = hm.keySet();
        Iterator it = set.iterator();
        while (it.hasNext()){
        Integer iw = it.next();
            System.out.println(iw.intValue());

        }
    }
}

  • A. Compile-time error; Set is an interface and cannot be instantiated.
  • B. Compile-time error; HashMap has no keySet method.
  • C. Compilation is fine but an error occurs at runtime.
  • D. Compile-time error; fault with arguments with put method.
  • E. Compile-time error; code error within the while loop.

 

Answer E is correct. Elements stored in the HashMap collection are of type Object. When returning these elements, they must be cast back to the required type, in this case Integer.

Last Updated ( Thursday, 03 August 2006 )

  home              contact us

 

©2006-2010 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground