Hashing

The Data

Search abstract data type

Java interface

Associative arrays in scripting languages

Many programming languages, particularly those designed for scripting support associative arrays implemented with hashes. The implementation technique is so common that the associative array is often called a “hash%rdquo; by programmers of those languages.

Perl

Perl was one of the first programming languages to provide hashes as a built-in datatype. In fact, one of the main reasons for programmers converting to Perl in the early-90’s was its support for hashes.

In Perl a hash can be created and initialized with a single statement.

%numSeats = (
  CSCI181 => 18,
  'HUM 224' => 180
) ;

Once an hash has been defined, it can be accessed with a minor modification of the usual array syntax.

  $numSeats{'HUM 224'} = 10 * $numSeats{'CSCI181'} ;

Python

Python implements hashes with the dictionary and uses the same syntax for accessing hash and array elements.

numSeats = ['CSCI181': 18, 'HUM 224' 180] ;
numSeats['HUM 224'] = 10 * numSeats['CSCI181'] ;

JavaScript

In JavaScript, every Object is implemented with an associative array.

numSeats = {
  CSCI181: 18,
  'HUM 224' 180
} ;
numSeats['HUM 224'] = 10 * numSeats.CSCI181 ;

Note that hashes can be accessed using C/Java style field selectors in addtional to normal array lookup.

JavaScript, like PHP, even implements regular arrays with hashes. The array index V[202] will be implemented as the hash index V["202"]. In web scripting languages, these minor inefficiences can be ignored.

Java and C++

Both the C++ Standard Template Libary (STL) and the Java collection framework (JCF) has a Map that corresponds to a hash table.

Because C++ supports operator overloading, it is possible to overload the array index operator [ ] and use the array lookup syntax in surprising ways.

PokerCard jackDiamond("jack", "diamond") ;
cardValue[jackDiamond] = 10 ;

Three simple implementations

One nice implementation

Java implementation

6.046 lecture