Powered by Blogger.

java.util.HashMap in detail with a program

>> Friday, September 12, 2014

HashMap is a class from java.util package and extends AbstractMap, implements Map,Cloneable and Serializable interfaces. HashMap contains Key,Value parameters we can denote it as HashMap<Key,Value> or HashMap<k,v>.Map allows only one null key and many null values and all the methods in HashMap are not synchronized. HashMap is an unordered collection , means the keys and values will not maintain insertion order.
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
Let us know the terminology used in HashMap.

Capacity: is the number of buckets in the hash table.

Initial Capacity: The capacity at the time the hash table is created.The default Initial Capacity is 16.

Load Factor: The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.The default load factor is 0.75

Bucket: Bucket is a slot can have multiple key-value pairs.

hash function: Hash function will generates unique hashcode using hashing technique for the given key and values.

Iterator in the HashMap is fail-fast. This means Iterator will produce exeception if concurrent
updates are made to the HashMap. In case of a single thread, using HashMap is faster than the HashTable.

As mentioned above HashMap is unsynchronized. But by using Collections.synchronizedMap(new HashMap( )); we can make the HashMap object synchronized.

In HashMap put and get methods will take the main role to insert and retrieve the values using keys. Based on number of keys and values pairs hash function distributes in buckets.Here 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.

When we pass Key and Value object  to put( ) method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic.

Simple program on HashMap

package com.javabynataraj;
//http://javabynataraj.blogspot.com
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HasMapTest {
 public static void main(String[] args) {
  Map<Integer, String> hmap = new HashMap<Integer, String>();
  hmap.put(100, "Chennai");
  hmap.put(null, null);
  hmap.put(null, null);
  hmap.put(200, null);
  hmap.put(100, null);
  hmap.put(300, null);
  hmap.put(200, "Hyderabad");
  hmap.put(400, "Bangalore");
  hmap.put(500, "Vijayavada");
  System.out.println(hmap);

  //iterate the hashmap using Map.Entry and Returns a Set -
   //view of the mappings contained in this map.
  Set set = hmap.entrySet();
  Iterator ite = set.iterator();
  System.out.println("HashMap keys and values: ");
  while (ite.hasNext()) {
   Map.Entry entry = (Map.Entry) ite.next();
   System.out.println(entry.getKey() + " -- " 
           + entry.getValue());
  }
  //values() method returns collection view of values
  System.out.println(hmap.values());
  
  //clear() method removes all of the mappings from this map. 
  //The map will be empty after this call returns.
  hmap.clear();
  System.out.println("after clearing hmap");
  System.out.println(hmap);
 }
}
Output:
{null=null, 100=null, 200=Hyderabad, 500=Vijayavada, 400=Bangalore, 300=null}
HashMap keys and values: 
null -- null
100 -- null
200 -- Hyderabad
500 -- Vijayavada
400 -- Bangalore
300 -- null
[null, null, Hyderabad, Vijayavada, Bangalore, null]
after clearing hmap
{}
HashMap Constructors:
  1. public HashMap(int initialCapacity,float loadFactor) - Constructs an empty HashMap with the specified initial capacity and load factor. 
  2.  public HashMap(int initialCapacity) - Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75). 
  3.  public HashMap( ) - Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). 
  4. public HashMap(Map<? extends K,? extends V> m) - Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.
HashMap methods:
  1. public void clear( ) - Removes all of the mappings from this map. The map will be empty after this call returns.
  2. public boolean containsValue(Object value)- Returns true if this map maps one or more keys to the specified value.
  3. public Object clone( ) - Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
  4. public Set<K> keySet( ) - Returns a Set view of the keys contained in this map.
  5. public V remove(Object key) - Removes the mapping for the specified key from this map if present.
  6. public V put(K key, V value) - Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
  7. public void putAll(Map<? extends K,? extends V> m) - Copies all of the mappings from the specified map to this map. 
  8. public boolean containsKey(Object key) - Returns true if this map contains a mapping for the specified key.
  9. public boolean isEmpty() - Returns true if this map contains no key-value mappings.
  10. public int size() - Returns the number of key-value mappings in this map.
  11. public Set<Map.Entry<K,V>> entrySet() - Returns a Set view of the mappings contained in this map. 
have a look at java docs for more detail.

Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.