java hash table demo

Hashtable in Java maps keys to values. In the demo below, the key is of string type and the value is of integer type. Once the hash table is defined, you can use the put to put a key and a value to the hash table. To loop through each key and value pairs, first get the keys from the hash table by calling keys() method on the hash table and save it as Enumeration object. Then loop though each key and get the value from the has table. For demonstration purpose, the values in here are integers, but it could any other types of data, either be primitive types or any other object types such as a list or a customer object type.

import java.util.Enumeration;
import java.util.Hashtable;

public class HashTableDemo {
   public static void main(String args[]) {
      // Creating a hash table, with key of type String, value of type Integer
      Hashtable<String, Integer> scores = new Hashtable<String, Integer>();
      Enumeration<String> names;
      String str;
      int score;

      scores.put("Amy", 74);
      scores.put("Ben", 82);
      scores.put("Carol", 80);
      scores.put("Denny", 92);
      scores.put("Edward", 91);

      // Show all scores in hash table.
      names = scores.keys();
      while(names.hasMoreElements()) {
         str = (String) names.nextElement();
         System.out.println(str + ": " +
      System.out.println("\nAdd 10 points for Amy\n........................");
      score = scores.get("Amy");
      scores.put("Amy", score + 10);
      System.out.println("Amy's new score: " + scores.get("Amy"));


Edward: 91
Amy: 74
Ben: 82
Denny: 92
Carol: 80

Add 10 points for Amy
Amy's new score: 84

Search within Codexpedia

Custom Search

Search the entire web

Custom Search