Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
Mar 13, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Hashtable Key Replacement

Most Java programmers know that adding an object to a Hashtable using a key already stored in the Hashtable will cause the previously-added object to be "dropped" from the table and replaced with the newly-added one. However, there is often confusion over precisely when two keys are considered equal. Some programmers assume that two keys are the same whenever their hash code values are the same, which is partially correct, but not the entire answer. Besides having the same hash code value, the equals() method also must return true when the two objects are compared to one another:
import java.util.*;
public class KeyTest {
	public static void main(String[] args) {
		Hashtable table = new Hashtable();
		table.put(new HashtableKey(123, "Red"), "First Red");
		table.put(new HashtableKey(123, "Blue"), "First Blue");
		table.put(new HashtableKey(456, "Blue"), "Another Blue");
		table.put(new HashtableKey(123, "Red"), "Another Red");
		Enumeration keys = table.keys();
		while (keys.hasMoreElements()) {
		}  //  while (keys.hasMoreElements())
	}  //  public static void main(String[] args)
}  //  public class KeyTest

class HashtableKey {
	int hashValue;
	String name;
	public HashtableKey(int hash, String nameval) {
		hashValue = hash;
		name = nameval;
	}  //  HashtableKey
	public int hashCode() {
		return hashValue;
	}  //  public int hashCode()
	public boolean equals(Object compare) {
		if (compare instanceof HashtableKey) {
			HashtableKey hk = (HashtableKey) compare;
			if (name.equals(hk.name)) return true;
		}  //  if (compare instanceof HashtableKey)
		return false;
	}  //  public boolean equals()
}  //  class HashtableKey
In this example, only the first and last keys added to the Hashtable meet the criteria for identical keys. As a result, the first object ("First Red") will be dropped from the Hashtable when the last one ("Another Red") is added, which produces this output:
Another Blue
First Blue
Another Red
Brett Spell
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date