Search the Site

Sponsors

bottom corner

Java hashtable sample usage

This note lists some practical examples for Java hashtable.

This page is filed under keyword(s): java.

A hashtable stores key-value pairs. In Java, it can be found in the package java.util.Hashtable. The examples below demonstrates some ways hashtables can be used in Java.

Instantiating a Hashtable

// Generic hashtable
Hashtable hashtable = new Hashtable();
// Hashtable with a specified initial size
Hashtable hashtable = new Hashtable(100);

Adding Data

hashtable.put("A", 1);
hashtable.put("B", 2);

In the example above, "A" and "B" are the keys, and 1 and 2 are the corresponding values.

Displaying Hashtable Info

// General info
System.out.println("Is Empty (returns true/false)?: " + hashtable.isEmpty());
System.out.println("Hashtable size (returns integer): " + hashtable.size());
// Query by key
System.out.print("Contains key \"A\" (returns true/false)?: " + hashtable.containsKey("A"));
// Query by value
System.out.print("Contains value 1 (returns true/false)?: " + hashtable.contains(1));

Getting Data

// Get by a particular key
System.out.print("Value for Key \"A\" is: " + hashtable.get("A"));
// Get all
for (String key : hashtable.values()) {
	// ...
}

Removing Data

hashtable.remove("A");

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): java.
Author: C. Peter Chen
Last updated: 26 May 2009

bottom corner