Java Reference
In-Depth Information
}
return result ;
Note that the above procedure is already implemented in Java in the String
class by the hashCode method. With that conversion procedure, two strings are
very likely to be converted into different integers. Now we create a hash table
HashTable that is an array of given size m . Then we hash string s using its
corresponding integer k into an index h ( k )of HashTable , ranging from 0 to m
1 using a hash function h . This is done simply by taking the modulo operation
(symbol % in Java) of the integer resulting from the conversion procedure. In
order to avoid hashing strings into the same array cell, we choose m to be prime
(here, m = 23):
h ( k )= k
mod m, where m is a prime number .
The code for hashing a set of strings is given below:
Program 7.18 Hashing a set of strings into a hash table
static int m=23;
// Note that m is a static variable
static int HashFunction( int l)
{ return l%m; }
public static void main ( String [ ] args )
{ String [] animals= { "cat" , "dog" , "parrot" , "horse" , "fish" ,
"shark" , "pelican" , "tortoise" , "whale" , "lion" ,
"flamingo" , "cow" , "snake" , "spider" , "bee" , "peacock" ,
"elephant" , "butterfly" } ;
int i;
String
[] HashTable= new String [m];
for (i=0;i < m; i ++)
HashTable [ i ]= new String( "-->" );
for (i=0;i < animals . length ; i++)
{ int pos=HashFunction(String2Integer (animals [ i ]) ) ;
HashTable [ pos]+=( "" +animals [ i ] ) ;
}
for (i=0;i < m; i ++)
System . out . println ( "Position " +i+ "\t" +HashTable [ i ]) ;
}
Compiling and executing the program, we get the following result:
Position 0
--> whale
Position 1
--> snake
Position 2
-->
Position 3
-->
 
Search WWH ::




Custom Search