Hash Tables in Java

A Well-known data structure for finding objects quickly is the hash table.  A hash table computes an integer called the hash code, for each object. A hash code is an integer that is somehow derived from the instance fields of an object, preferably such that objects with different data yield different codes.



If you define your own classes, you are responsible for implementing your own hashCode method.

In Java, hash table are implemented as arrays of linked lists. Each list is called a bucket.

Hash tables can be used to implement several important data structures. The simplest among them is the set type. A set is a collection of elements without duplicates. The add method of a set first tries to find the object to be added, and adds it only if it is not yet present.  The Java collections library supplies a HashSet class that implements a set based on a hash table.  The contains method is redefined to make a fast lookup to find if an element is already present in the set. It checks only one bucket and not all elements in the collection. You would only use a HashSet if you don't care about the ordering of the elements in the collection.


The TreeSet class is similar to the hash set, with one added improvement. A tree set is a
sorted collection.


The Java library supplies two general-purpose implementations for maps: HashMap and TreeMap. Both classes ipmlemnet the Map interface.


A hash map hashes the keys, and a tree map uses a total ordering on the keys to organize
them in a search tree.

(Text above extracted from Core Java)


Hashtable is a java public synchronized class and a member of Collections Framework in Javawhich is used to implement the mapping of Java objects as keys and value associations. In order to be members of a hashtable data structure object, both the key and its associated values must be non-null objects. Hashtable class is an extension of Dictionary class belonging to the java.util library and it implements Map, Cloneable and Serializable interfaces.
The objects used as keys of a hashtable object implement "hashCode" and "equals" methods in order to store and retrieve objects from the hashtable data structure object

No comments: