How do I use the HashMap class?

Category: java.util, viewed: 16653 time(s).

This examples demonstrate you how to use the HashMap class to map some values. In this example we map the error codes with their description. To store some data into the map we use the put() method and to get it back use the get() method. And we can also interate the map using the available key sets of the map.

package org.kodejava.example.lang;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map errors = new HashMap();

        // mapping some data in the map
        errors.put("404", "Resource not found.");
        errors.put("403", "Access forbidden.");
        errors.put("500", "General server error.");

        // reading data from the map
        String errorDesc = (String) errors.get("404");
        System.out.println("Error 404: " + errorDesc);

        // iterating the map by it's keys
        Iterator iterator = errors.keySet().iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            System.out.println("Error " + key + " means " + errors.get(key));
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats