View RSS Feed

My Java Tips

Example - HashMap

Rating: 1 votes, 1.00 average.
by , 11-02-2011 at 06:11 PM (1511 Views)
Map is an object that stores key/volume pairs. Given a key, you can find its value. Keys must be unique, but values may be duplicated. The HashMap class provides the primary implementation of the map interface. The HashMap class uses a hash table to implementation of the map interface. This allows the execution time of basic operations, such as get() and put() to be constant.


This code shows the use of HaspMap. In this program HashMap maps the names to account balances.

Java Code:
import java.util.*;

public class HashMapDemo {

  public static void main(String[] args) {

    HashMap hm = new HashMap();
    hm.put("A", new Double(3434.34));
    hm.put("B", new Double(123.22));
    hm.put("C", new Double(1200.34));
    hm.put("D", new Double(99.34));
    hm.put("E", new Double(-19.34));
    Set set = hm.entrySet();

    Iterator i = set.iterator();

    while(i.hasNext()){
      Map.Entry me = (Map.Entry)i.next();
      System.out.println(me.getKey() + " : " + me.getValue() );
    }

    //deposit into A's Account
    double balance = ((Double)hm.get("A")).doubleValue();
    hm.put("A", new Double(balance + 1000));

    System.out.println("A new balance : " + hm.get("Rohit"));

  }
}
Output Screen:

A : 3434.34
B : 1200.34
C : -19.34
D : 123.22
E : 99.34
A new balance : 4434.34

Submit "Example - HashMap" to Facebook Submit "Example - HashMap" to Digg Submit "Example - HashMap" to del.icio.us Submit "Example - HashMap" to StumbleUpon Submit "Example - HashMap" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments