When you perform a lookup in a Hashtable, the key is converted into a hash. Now using that hashed value, does it directly map to a memory location, or are there more steps?
Just trying to understand things a little more under the covers.
And what other key based lookup data structures are there and why are they slower than a hash?
A Hash (aka Hash Table) implies more than a Map (or Associative Array).
In particular, a Map (or Associative Array) is an Abstract Data Type:
While a Hash table is an implementation of a Map (although it could also be considered an ADT that includes a “cost”):
Thus it is an implementation-detail leaking out: a
HashMapis aMapthat uses a Hash-table algorithm and thus provides the expected performance characteristics of such an algorithm. The “leaking” of the implementation detail is good in this case because it provides some basic [expected] bound guarantees, such as an [expected]O(1)— or constant time —get.Hint: a hash function is important part of a hash-table algorithm and sets a
HashMapapart from otherMapimplementations such as aTreeMap(that uses a red-black tree) or aConcurrentSkipListMap(that uses a skip list).Another form of a Map is an Association List (or “alist”, which is common in LISP programming). While association lists are
O(n)forget, they can have much less overhead for smalln, which brings up another point: Big-Oh describes limiting behavior (asn -> infinity) and does not address the relative performance for a particular [smallish]n:Please refer to the links above (including the javadoc) for the basic characteristics and different implementation strategies — anything else I say here is already said there (or in other SO answers). If there are specific questions, open a new SO post if warranted 🙂
Happy coding.
Here is the source for the
HashMapimplementation that is in OpenJDK 7. Looking at theputmethod shows that it a simple chaining as a collision-resolution method and that the underlying “bucket array” will grow by a factor of 2 each resize (which is triggered when the load factor is reached). The load factor and amortized performance expectations — including those of the hashing function used — are covered in the class documentation.