Home  >  Core Java

Example of HashMap in Java

By Arvind Rai, June 09, 2013
java.util.HashMap implements Map interface. HashMap works on the basis of key value pair. HashMap works same like Hash Table. But HashMap is faster than Hash Table. HashMap is not thread safe but Hash Table is thread safe. HashMap allows adding null values. Find example of Map.
HashMapDemo.java
package com.concretepage.util;
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
    public static void main(String[] args) {
        Map<Integer,Bean> map = new HashMap<Integer,Bean>();
        Bean b1 = new Bean("A");
        Bean b2 = new Bean("B");
        Bean b3 = new Bean("C");
        map.put(1, b1);
        map.put(2, b2);
        map.put(3, b3);
        System.out.println(map.size());
        System.out.println(map.get(1).name);
        for(Bean b: map.values()){
          System.out.println(b.name);    
        }
    }
}
class Bean {
    public String name;
    public Bean(String name) {
        this.name = name;
    }
 }
Output
3
A
A
B
C 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us