devxlogo

Hashtable Key Replacement

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()) {			System.out.println(table.get(keys.nextElement()));		}  //  while (keys.hasMoreElements())	}  //  public static void main(String[] args)}  //  public class KeyTestclass 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 BlueFirst BlueAnother Red
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist