• Java Data Structures Tutorial

Java Data Structures - Creating a hash table



The Java package java.util provides a class named HashTable which represents the hash table. This stores key/value pairs while using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

You can create a hash table by instantiating the HashTable class.

HashTable hashTable = new HashTable();

Example

import java.util.Hashtable;

public class CreatingHashTable {
   public static void main(String args[]) {
      Hashtable hashTable = new Hashtable();
      hashTable.put("Ram", 94.6);
      hashTable.put("Rahim", 92);
      hashTable.put("Robert", 85);
      hashTable.put("Roja", 93);
      hashTable.put("Raja", 75);
      System.out.println(hashTable);    		  
   }
}

Output

{Rahim = 92, Roja = 93, Raja = 75, Ram = 94.6, Robert = 85}
Advertisements