| | |
    Java Beginner Home
    Table of Contents
    Introduction to Java
    Getting Started with Java
    Basic Language Elements
    Java Operators
    Java Control Statements
    Java Access Modifiers
    Classes and Objects
    Java Constructors
    Object Serialization
    Java Class Inheritance
    Java Object Type Casting
    Abstract class and Interface
    Java Method Overiding
    Java toString Method
    Java String Class
    Java toString Method
    Java String Comparison
    Java StringBuffer
    Java Exceptions
    Singleton Pattern
    Java Threads Tutorial
    Java Collections Framework
    Java Date Util
    Swing Tutorial
    Feedback
    Java books

Java HashMap

  • The java HashMap class does not guarantee that the order will remain constant over time.
  • This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
  • The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

To prevent unsynchronized access to the Map: Map m = Collections.synchronizedMap(new HashMap(...));




Below is a HashMap Example used to store the number of words that begin with a given letter

/*
 *  Using a HashMap to store the number of words that begin with a given letter.
 */
import java.util.HashMap;

public class HashMapExample {

	static String[] names = { "heman", "bob", "hhh", "shawn", "scot","shan", "keeth" };
	private static HashMap counter = new HashMap();
	private static Integer cnt = null;
	public static void main(String args[]) {
		for (int i = 0; i < names.length; i++) {
			cnt = (Integer) (counter.get(new Character(names[i].charAt(0))));
			if (cnt == null) {
				counter.put(new Character(names[i].charAt(0)),new Integer("1"));
			} else {
				counter.put(new Character(names[i].charAt(0)),
						new Integer(cnt.intValue() + 1));
			}
		}
		System.out.println("\nnumber of words beginning with each letter is shown below ");
		System.out.println(counter.toString());
	}
}

 

Output

number of words beginning with each letter is shown below
{s=3, b=1, k=1, h=2}

Download  HashMapExample.java

 

 
Page 5 of 8
1
5



 
 
    Java is a trademark of Sun Microsystems, Inc.
| | |
© Copyright 2007-08 javabeginner.com