Hashtable Hash Code Example

Hashtable Hash Code Example

Three programs are given on Hashtable.

  1. Hashtable General: Uses the methods like elements, containsKey, put, get, contains and keys.
  2. Hashtable Generics: Creates generics Hashtable storing strings and integers and uses the methods like keySet, values, hashCode, putAll, clear, size, iterator, remove and isempty etc.
  3. Hashtable Special: Uses the methods like clone(), hashCode() and the values are printed in the ascending order of keys.

It is advised to read Hashtable About before going through this program to get acquainted with the properties, constructors and methods of Hashtable.

Example on Hashtable Hash Code

The special operations in this third program are comparing two hash tables with hash code, cloning hashtable and printing the elements in the ascending order.

Hashtable Hash Code
Output screenshot of Hashtable Hash Code Example

Hashtable objects ht1 and ht2 with the same elements are created.

hashCode() method returns the hash code value of the hash table. If the elements are same, both the hash tables return the same hash code. For this reason, ht1 and ht2 hash codes are same and when they are same, the if statement is executed.

The clone() method of Hashtable is used to clone the Hashtable object ht1. The cloned object ht3 contains the same elements of ht1. For this reason, the hash codes of ht1 and ht3 are same. This is known as hashing.

The principle is TreeSet prints its elements in natural order (ascending order) implicitly. The hash table ht1 elements are passed to TreeSet through Set interface. TreeSet implements SortedSet and again SortedSet extends Set. TreeSet returns the keys and the values are obtained from keys in the while loop.

About Hashing and Hashcode

Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.

Hashing is process of converting a string or object into a 32-bit hashcode integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination with equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.

Leave a Reply

Your email address will not be published. Required fields are marked *