Saturday, 23 May 2015

HashMap Of Java Collection With Easy Example

java.util.HashMap<K,V>   is used to implement Map data structure.It extends AbstractMap class , and implements Map interface.Internally HashMap use hash table to store objects. 

Characteristics of HashMap  

1. HashMap store objects as Key value Pair.
2. We can get value by its unique key.
3. HashMap can store only one null value as a key. 
4. HashMap is not thread safe, Multiple thread can access one HashMap simultaneously
5. HashMap does not maintain the order. 

Example HashMap<K,V> 



package com.javasuitor.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {

 public static void main(String[] args) {
  
  // Map contains data in  Key, Value Pair, keys will be unique
  Map<Integer,String> studentMap = new HashMap<Integer,String>();
  
  studentMap.put(101, "Ashok Singh");
  studentMap.put(102, "Arvind");  
  studentMap.put(103, "Monika");
  studentMap.put(104, "Aakanksha");
  studentMap.put(105, "Sourabh");  
  
  // We can pass null as a key only once in map.
  studentMap.put(null,null);
  
  // If you pass duplicate key then value will be overwritten. 
  
  studentMap.put(null,"No name");
  
  Set<Integer> keys = studentMap.keySet();
  
  // View all values
  for(Integer i : keys){
   System.out.println("Key :" + i +" Value : "+ studentMap.get(i));
  }
    
  
 }
}

Output :




Key :null Value : No name
Key :102 Value : Arvind
Key :103 Value : Monika
Key :101 Value : Ashok Singh
Key :104 Value : Aakanksha
Key :105 Value : Sourabh




Difference Between HashTable and HashMap


HashTable is very similar to HashMap. Difference between HashTable and HashMap are :

1. HashTable can not store null value.

2. HashTable is thread safe, multiple thread cannot access HashTable simultaneously.
3. HashMap is faster than HashTable.


Reference :

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html


3 comments:

  1. if we can access every element of map using key than why we need Hashing?

    ReplyDelete
    Replies
    1. Your interest in topic is appreciable. In java every object has its hashCode. When we use get method of HashMap , internally JVM call hashCode(key) method of key object. it return hashCode value for key which is always an integer number. JVM use hashCode as argument of hash(int hashCode) method .hash method returns the address where object store as key, value pair. Here key can be an integer number, a string or an object. So for mapping of key to memory address where object actually store JVM need hashing.

      Delete