Java Program to Implement Hash Tables Chaining with Binary Trees

«
»
This is a Java Program to implement hash tables chaining with Binary Trees. A hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found. In order to prevent collision, hash tables are chained with another data structure ( Binary Trees in this case ).

Here is the source code of the Java program to implement hash tables chaining with Binary Trees. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  *    Java Program to Implement Hash Tables Chaining with Binary Trees
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. /* Node for Binary Tree */
  8. class BTNode
  9. {
  10.     BTNode left, right;
  11.     int data;
  12.  
  13.     /* Constructor */
  14.     public BTNode(int x)
  15.     {
  16.         data = x;
  17.         left = null;
  18.         right = null;
  19.     }
  20. }
  21.  
  22. /* Class HashTableChainingBinaryTree */
  23. class HashTableChainingBinaryTree
  24. {
  25.     private BTNode[] table;
  26.     private int size ;
  27.  
  28.     /* Constructor */
  29.     public HashTableChainingBinaryTree(int tableSize)
  30.     {
  31.         table = new BTNode[ nextPrime(tableSize) ];
  32.         size = 0;
  33.     }
  34.     /* Function to check if hash table is empty */
  35.     public boolean isEmpty()
  36.     {
  37.         return size == 0;
  38.     }
  39.     /* Function to clear hash table */
  40.     public void makeEmpty()
  41.     {
  42.         int l = table.length;
  43.         table = new BTNode[l];
  44.         size = 0;
  45.     }
  46.     /* Function to get size */
  47.     public int getSize()
  48.     {
  49.         return size;
  50.     }
  51.     /* Function to insert an element */
  52.     public void insert(int val)
  53.     {
  54.         size++;
  55.         int pos = myhash(val);        
  56.         BTNode root = table[pos];
  57.         root = insert(root, val);
  58.         table[pos] = root;        
  59.     }
  60.     /* Function to insert data */
  61.     private BTNode insert(BTNode node, int data)
  62.     {
  63.         if (node == null)
  64.             node = new BTNode(data);
  65.         else
  66.         {
  67.             if (data <= node.data)
  68.                 node.left = insert(node.left, data);
  69.             else
  70.                 node.right = insert(node.right, data);
  71.         }
  72.         return node;
  73.     }
  74.     /* Function to remove an element */
  75.     public void remove(int val)
  76.     {
  77.         int pos = myhash(val);        
  78.         BTNode root = table[pos];
  79.         try
  80.         {
  81.             root = delete(root, val);    
  82.             size--;
  83.         }
  84.         catch (Exception e)
  85.         {
  86.             System.out.println("\nElement not present\n");        
  87.         }        
  88.         table[pos] = root;        
  89.     }
  90.     /* Function to remove an element */
  91.     private BTNode delete(BTNode root, int k)
  92.     {
  93.         BTNode p, p2, n;
  94.         if (root.data == k)
  95.         {
  96.                BTNode lt, rt;
  97.             lt = root.left;
  98.             rt = root.right;
  99.             if (lt == null && rt == null)
  100.                 return null;
  101.             else if (lt == null)
  102.             {
  103.                 p = rt;
  104.                 return p;
  105.             }
  106.             else if (rt == null)
  107.             {
  108.                 p = lt;
  109.                 return p;
  110.             }
  111.             else
  112.             {
  113.                 p2 = rt;
  114.                 p = rt;
  115.                 while (p.left != null)
  116.                     p = p.left;
  117.                 p.left = lt;
  118.                 return p2;
  119.             }
  120.         }
  121.         if (k < root.data)
  122.         {
  123.             n = delete(root.left, k);
  124.             root.left = n;
  125.         }
  126.         else
  127.         {
  128.             n = delete(root.right, k);
  129.             root.right = n;             
  130.         }
  131.         return root;
  132.     }
  133.     /* Function myhash */
  134.     private int myhash(Integer x )
  135.     {
  136.         int hashVal = x.hashCode( );
  137.         hashVal %= table.length;
  138.         if (hashVal < 0)
  139.             hashVal += table.length;
  140.         return hashVal;
  141.     }
  142.     /* Function to generate next prime number >= n */
  143.     private static int nextPrime( int n )
  144.     {
  145.         if (n % 2 == 0)
  146.             n++;
  147.         for ( ; !isPrime( n ); n += 2);
  148.  
  149.         return n;
  150.     }
  151.     /* Function to check if given number is prime */
  152.     private static boolean isPrime( int n )
  153.     {
  154.         if (n == 2 || n == 3)
  155.             return true;
  156.         if (n == 1 || n % 2 == 0)
  157.             return false;
  158.         for (int i = 3; i * i <= n; i += 2)
  159.             if (n % i == 0)
  160.                 return false;
  161.         return true;
  162.     }
  163.     /* printing hash table */
  164.     public void printHashTable ()
  165.     {
  166.         System.out.println();
  167.         for (int i = 0; i < table.length; i++)
  168.         {
  169.             System.out.print ("Bucket " + i + ":  ");            
  170.             inorder(table[i]);
  171.             System.out.println();
  172.         }
  173.     }  
  174.     /* inorder traversal */
  175.     private void inorder(BTNode r)
  176.     {
  177.         if (r != null)
  178.         {
  179.             inorder(r.left);
  180.             System.out.print(r.data +" ");
  181.             inorder(r.right);
  182.         }
  183.     }     
  184. }
  185.  
  186. /* Class HashTableChainingBinaryTreeTest */
  187. public class HashTableChainingBinaryTreeTest
  188. { 
  189.     public static void main(String[] args) 
  190.     {
  191.         Scanner scan = new Scanner(System.in);
  192.         System.out.println("Hash Table Test\n\n");
  193.         System.out.println("Enter size");
  194.         /* Make object of HashTableChainingBinaryTree  */
  195.         HashTableChainingBinaryTree htcbt = new HashTableChainingBinaryTree(scan.nextInt() );
  196.  
  197.         char ch;
  198.         /*  Perform HashTableChainingBinaryTree operations  */
  199.         do     
  200.         {
  201.             System.out.println("\nHash Table Operations\n");
  202.             System.out.println("1. insert ");
  203.             System.out.println("2. remove"); 
  204.             System.out.println("3. clear");
  205.             System.out.println("4. size"); 
  206.             System.out.println("5. check empty");
  207.  
  208.             int choice = scan.nextInt();            
  209.             switch (choice)  
  210.             {  
  211.             case 1 : 
  212.                 System.out.println("Enter integer element to insert");
  213.                 htcbt.insert( scan.nextInt() ); 
  214.                 break;                          
  215.             case 2 :                 
  216.                 System.out.println("Enter integer element to delete");
  217.                 htcbt.remove( scan.nextInt() ); 
  218.                 break;                        
  219.             case 3 : 
  220.                 htcbt.makeEmpty();
  221.                 System.out.println("Hash Table Cleared\n");
  222.                 break;
  223.             case 4 : 
  224.                 System.out.println("Size = "+ htcbt.getSize() );
  225.                 break; 
  226.             case 5 : 
  227.                 System.out.println("Empty status = "+ htcbt.isEmpty() );
  228.                 break;        
  229.             default : 
  230.                 System.out.println("Wrong Entry \n ");
  231.                 break;    
  232.             }
  233.             /* Display hash table */ 
  234.             htcbt.printHashTable();    
  235.  
  236.             System.out.println("\nDo you want to continue (Type y or n) \n");
  237.             ch = scan.next().charAt(0);                        
  238.         } while (ch == 'Y'|| ch == 'y');   
  239.     }
  240. }

advertisement
Hash Table Test
 
 
Enter size
5
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
56
 
Bucket 0:
Bucket 1:  56
Bucket 2:
Bucket 3:
Bucket 4:
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
78
 
Bucket 0:
Bucket 1:  56
Bucket 2:
Bucket 3:  78
Bucket 4:
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
23
 
Bucket 0:
Bucket 1:  56
Bucket 2:
Bucket 3:  23 78
Bucket 4:
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
44
 
Bucket 0:
Bucket 1:  56
Bucket 2:
Bucket 3:  23 78
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
60
 
Bucket 0:  60
Bucket 1:  56
Bucket 2:
Bucket 3:  23 78
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
97
Wrong Entry
 
 
Bucket 0:  60
Bucket 1:  56
Bucket 2:
Bucket 3:  23 78
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
97
 
Bucket 0:  60
Bucket 1:  56
Bucket 2:  97
Bucket 3:  23 78
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
1
Enter integer element to insert
7
 
Bucket 0:  60
Bucket 1:  56
Bucket 2:  7 97
Bucket 3:  23 78
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
2
Enter integer element to delete
78
 
Bucket 0:  60
Bucket 1:  56
Bucket 2:  7 97
Bucket 3:  23
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
4
Size = 6
 
Bucket 0:  60
Bucket 1:  56
Bucket 2:  7 97
Bucket 3:  23
Bucket 4:  44
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
3
Hash Table Cleared
 
 
Bucket 0:
Bucket 1:
Bucket 2:
Bucket 3:
Bucket 4:
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. clear
4. size
5. check empty
5
Empty status = true
 
Bucket 0:
Bucket 1:
Bucket 2:
Bucket 3:
Bucket 4:
 
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.