Java Reference
In-Depth Information
7.8.2 Solving collisions with linked lists
Instead of considering an array of strings as we previously did, we now consider
an array of linked lists. Each cell of the array will store a reference to the head
of the linked list it refers to. When there is hash collision, we just add the
element to the linked list of its hashed index. The code for initializing the hash
table and filling it with the data-set is given below:
ListString
[] HashTable= new ListString [m];
for (i=0;i < m; i ++)
HashTable [ i ]= null ;
for (i=0;i < animals . length ; i++)
int s2int=String2Integer(animals [ i ]) ;
int pos=HashFunction( s2int ) ;
HashTable[pos]=ListString . Insert(animals [ i ] ,HashTable[pos ]) ;
}
for (i=0;i < m; i ++)
ListString . Display(HashTable[ i ]) ;
Executing the above code yields:
whale-->null
bee-->snake-->null
null
spider-->null
butterfly-->null
null
null
cow-->null
shark-->null
null
null
null
fish-->null
peacock-->cat-->null
null
tortoise-->dog-->null
horse-->null
flamingo-->null
null
pelican-->null
lion-->parrot-->null
elephant-->null
null
 
Search WWH ::




Custom Search