Java Program to Implement Hash Tables with Linear Probing

This is a Java Program to implement hash tables with Linear Probing. 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. Linear probing is a probe sequence in which the interval between probes is fixed (usually 1).

Here is the source code of the Java program to implement hash tables with Linear Probing. 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 Linear Probing Hash Table
  3.  **/ 
  4.  
  5. import java.util.Scanner;
  6.  
  7.  
  8. /** Class LinearProbingHashTable **/
  9. class LinearProbingHashTable
  10. {
  11.     private int currentSize, maxSize;       
  12.     private String[] keys;   
  13.     private String[] vals;    
  14.  
  15.     /** Constructor **/
  16.     public LinearProbingHashTable(int capacity) 
  17.     {
  18.         currentSize = 0;
  19.         maxSize = capacity;
  20.         keys = new String[maxSize];
  21.         vals = new String[maxSize];
  22.     }  
  23.  
  24.     /** Function to clear hash table **/
  25.     public void makeEmpty()
  26.     {
  27.         currentSize = 0;
  28.         keys = new String[maxSize];
  29.         vals = new String[maxSize];
  30.     }
  31.  
  32.     /** Function to get size of hash table **/
  33.     public int getSize() 
  34.     {
  35.         return currentSize;
  36.     }
  37.  
  38.     /** Function to check if hash table is full **/
  39.     public boolean isFull() 
  40.     {
  41.         return currentSize == maxSize;
  42.     }
  43.  
  44.     /** Function to check if hash table is empty **/
  45.     public boolean isEmpty() 
  46.     {
  47.         return getSize() == 0;
  48.     }
  49.  
  50.     /** Fucntion to check if hash table contains a key **/
  51.     public boolean contains(String key) 
  52.     {
  53.         return get(key) !=  null;
  54.     }
  55.  
  56.     /** Functiont to get hash code of a given key **/
  57.     private int hash(String key) 
  58.     {
  59.         return key.hashCode() % maxSize;
  60.     }    
  61.  
  62.     /** Function to insert key-value pair **/
  63.     public void insert(String key, String val) 
  64.     {                
  65.         int tmp = hash(key);
  66.         int i = tmp;
  67.         do
  68.         {
  69.             if (keys[i] == null)
  70.             {
  71.                 keys[i] = key;
  72.                 vals[i] = val;
  73.                 currentSize++;
  74.                 return;
  75.             }
  76.             if (keys[i].equals(key)) 
  77.             { 
  78.                 vals[i] = val; 
  79.                 return; 
  80.             }            
  81.             i = (i + 1) % maxSize;            
  82.         } while (i != tmp);       
  83.     }
  84.  
  85.     /** Function to get value for a given key **/
  86.     public String get(String key) 
  87.     {
  88.         int i = hash(key);
  89.         while (keys[i] != null)
  90.         {
  91.             if (keys[i].equals(key))
  92.                 return vals[i];
  93.             i = (i + 1) % maxSize;
  94.         }            
  95.         return null;
  96.     }
  97.  
  98.     /** Function to remove key and its value **/
  99.     public void remove(String key) 
  100.     {
  101.         if (!contains(key)) 
  102.             return;
  103.  
  104.         /** find position key and delete **/
  105.         int i = hash(key);
  106.         while (!key.equals(keys[i])) 
  107.             i = (i + 1) % maxSize;        
  108.         keys[i] = vals[i] = null;
  109.  
  110.         /** rehash all keys **/        
  111.         for (i = (i + 1) % maxSize; keys[i] != null; i = (i + 1) % maxSize)
  112.         {
  113.             String tmp1 = keys[i], tmp2 = vals[i];
  114.             keys[i] = vals[i] = null;
  115.             currentSize--;  
  116.             insert(tmp1, tmp2);            
  117.         }
  118.         currentSize--;        
  119.     }       
  120.  
  121.     /** Function to print HashTable **/
  122.     public void printHashTable()
  123.     {
  124.         System.out.println("\nHash Table: ");
  125.         for (int i = 0; i < maxSize; i++)
  126.             if (keys[i] != null)
  127.                 System.out.println(keys[i] +" "+ vals[i]);
  128.         System.out.println();
  129.     }   
  130. }
  131.  
  132. /** Class LinearProbingHashTableTest **/
  133. public class LinearProbingHashTableTest
  134. {
  135.     public static void main(String[] args)
  136.     {
  137.         Scanner scan = new Scanner(System.in);
  138.         System.out.println("Hash Table Test\n\n");
  139.         System.out.println("Enter size");
  140.         /** maxSizeake object of LinearProbingHashTable **/
  141.         LinearProbingHashTable lpht = new LinearProbingHashTable(scan.nextInt() );
  142.  
  143.         char ch;
  144.         /**  Perform LinearProbingHashTable operations  **/
  145.         do    
  146.         {
  147.             System.out.println("\nHash Table Operations\n");
  148.             System.out.println("1. insert ");
  149.             System.out.println("2. remove");
  150.             System.out.println("3. get");            
  151.             System.out.println("4. clear");
  152.             System.out.println("5. size");
  153.  
  154.             int choice = scan.nextInt();            
  155.             switch (choice)
  156.             {
  157.             case 1 : 
  158.                 System.out.println("Enter key and value");
  159.                 lpht.insert(scan.next(), scan.next() ); 
  160.                 break;                          
  161.             case 2 :                 
  162.                 System.out.println("Enter key");
  163.                 lpht.remove( scan.next() ); 
  164.                 break;                        
  165.             case 3 : 
  166.                 System.out.println("Enter key");
  167.                 System.out.println("Value = "+ lpht.get( scan.next() )); 
  168.                 break;                                   
  169.             case 4 : 
  170.                 lpht.makeEmpty();
  171.                 System.out.println("Hash Table Cleared\n");
  172.                 break;
  173.             case 5 : 
  174.                 System.out.println("Size = "+ lpht.getSize() );
  175.                 break;         
  176.             default : 
  177.                 System.out.println("Wrong Entry \n ");
  178.                 break;   
  179.             }
  180.             /** Display hash table **/
  181.             lpht.printHashTable();  
  182.  
  183.             System.out.println("\nDo you want to continue (Type y or n) \n");
  184.             ch = scan.next().charAt(0);                        
  185.         } while (ch == 'Y'|| ch == 'y');  
  186.     }
  187. }

Hash Table Test
 
 
Enter size
5
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
Na sodium
 
Hash Table:
Na sodium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
K potassium
 
Hash Table:
Na sodium
K potassium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
Fe iron
 
Hash Table:
Na sodium
K potassium
Fe iron
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
H hydrogen
 
Hash Table:
Na sodium
K potassium
Fe iron
H hydrogen
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
He helium
 
Hash Table:
Na sodium
K potassium
Fe iron
H hydrogen
He helium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
Ag silver
 
Hash Table:
Na sodium
K potassium
Fe iron
H hydrogen
He helium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
3
Enter key
Fe
Value = iron
 
Hash Table:
Na sodium
K potassium
Fe iron
H hydrogen
He helium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
2
Enter key
H
 
Hash Table:
Na sodium
K potassium
Fe iron
He helium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
3
Enter key
H
Value = null
 
Hash Table:
Na sodium
K potassium
Fe iron
He helium
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
1
Enter key and value
Au gold
 
Hash Table:
Na sodium
K potassium
Fe iron
He helium
Au gold
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
5
Size = 5
 
Hash Table:
Na sodium
K potassium
Fe iron
He helium
Au gold
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
4
Hash Table Cleared
 
 
Hash Table:
 
 
Do you want to continue (Type y or n)
 
y
 
Hash Table Operations
 
1. insert
2. remove
3. get
4. clear
5. size
5
Size = 0
 
Hash Table:
 
 
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

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 & discussions at Telegram SanfoundryClasses.