Java Program to Implement HashTables with Linear Probing Last Updated : 17 Jun, 2021 Comments Improve Suggest changes Like Article Like Report Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects. Suppose an object is to be assigned a key to it to make searching easy. To store the key/value pair, one can use a simple array like a data structure where keys (integers) can be used directly as an index to store values. However, in cases where the keys are large and cannot be used directly as an index, one should use hashing. In hashing, large keys are converted into small keys by using hash functions. The values are then stored in a data structure called hash table. Linear Probing, It may happen that the hashing technique is used to create an already used index of the array. In such a case, we can search for the next empty location in the array by looking into the next cell until we find an empty cell. This technique is called linear probing. There are three basic operations linked with linear probing which are as follows: SearchInsertDelete Implementation: Hash tables with linear probing by making a helper class and testing this in the main class. Example Java // Java Program to Implement Hash Tables with Linear Probing // Importing all classes from // java.util package // Importing all input output classes import java.io.*; import java.util.*; // Importing Scanner class as in do-while // inputs are entered at run-time when // menu is popped to user to perform desired action import java.util.Scanner; // Helper class - LinearProbingHashTable class LinearProbingHashTable { // Member variables of this class private int currentSize, maxSize; private String[] keys; private String[] vals; // Constructor of this class public LinearProbingHashTable(int capacity) { currentSize = 0; maxSize = capacity; keys = new String[maxSize]; vals = new String[maxSize]; } // Method 1 // Function to clear hash table public void makeEmpty() { currentSize = 0; keys = new String[maxSize]; vals = new String[maxSize]; } // Method 2 // Function to get size of hash table public int getSize() { return currentSize; } // Method 3 // Function to check if hash table is full public boolean isFull() { return currentSize == maxSize; } // Method 4 // Function to check if hash table is empty public boolean isEmpty() { return getSize() == 0; } // Method 5 // Function to check if hash table contains a key public boolean contains(String key) { return get(key) != null; } // Method 6 // Function to get hash code of a given key private int hash(String key) { return key.hashCode() % maxSize; } // Method 7 // Function to insert key-value pair public void insert(String key, String val) { int tmp = hash(key); int i = tmp; // Do-while loop // Do part for performing actions do { if (keys[i] == null) { keys[i] = key; vals[i] = val; currentSize++; return; } if (keys[i].equals(key)) { vals[i] = val; return; } i = (i + 1) % maxSize; } // Do-while loop // while part for condition check while (i != tmp); } // Method 8 // Function to get value for a given key public String get(String key) { int i = hash(key); while (keys[i] != null) { if (keys[i].equals(key)) return vals[i]; i = (i + 1) % maxSize; } return null; } // Method 9 // Function to remove key and its value public void remove(String key) { if (!contains(key)) return; // Find position key and delete int i = hash(key); while (!key.equals(keys[i])) i = (i + 1) % maxSize; keys[i] = vals[i] = null; // rehash all keys for (i = (i + 1) % maxSize; keys[i] != null; i = (i + 1) % maxSize) { String tmp1 = keys[i], tmp2 = vals[i]; keys[i] = vals[i] = null; currentSize--; insert(tmp1, tmp2); } currentSize--; } // Method 10 // Function to print HashTable public void printHashTable() { System.out.println("\nHash Table: "); for (int i = 0; i < maxSize; i++) if (keys[i] != null) System.out.println(keys[i] + " " + vals[i]); System.out.println(); } } // Main testing class // Main Class for LinearProbingHashTableTest public class GFG { // Main driver method public static void main(String[] args) { // Creating a scanner object // to take input from user Scanner scan = new Scanner(System.in); // Display messages System.out.println("Hash Table Test\n\n"); System.out.println("Enter size"); // maxSizeake object of LinearProbingHashTable LinearProbingHashTable lpht = new LinearProbingHashTable(scan.nextInt()); char ch; // Do-while loop // Do part for performing actions do // Menu is displayed // LinearProbingHashTable operations performed as // per keys Users enter 'y' to continue 'n' if // entered by user , the program terminates { // Menu // Display messages System.out.println("\nHash Table Operations\n"); System.out.println("1. insert "); System.out.println("2. remove"); System.out.println("3. get"); System.out.println("4. clear"); System.out.println("5. size"); // Reading integer using nextInt() int choice = scan.nextInt(); // Switch case switch (choice) { // Case 1 case 1: // Display message System.out.println("Enter key and value"); lpht.insert(scan.next(), scan.next()); // Break statement to terminate a case break; // Case 2 case 2: // Display message System.out.println("Enter key"); lpht.remove(scan.next()); // Break statement to terminate a case break; // Case 3 case 3: // Print statements System.out.println("Enter key"); System.out.println("Value = " + lpht.get(scan.next())); // Break statement to terminate a case break; // Case 4 case 4: lpht.makeEmpty(); // Print statement System.out.println("Hash Table Cleared\n"); // Break statement to terminate a case break; // Case 5 case 5: // Print statement System.out.println("Size = " + lpht.getSize()); break; // Default case // Executed when mentioned switch cases are not // matched default: // Print statement System.out.println("Wrong Entry \n "); // Break statement break; } // Display hash table lpht.printHashTable(); // Display message asking the user whether // he/she wants to continue System.out.println( "\nDo you want to continue (Type y or n) \n"); // Reading character using charAt() method to // fetch ch = scan.next().charAt(0); } while (ch == 'Y' || ch == 'y'); } } Output: Random action performed over Hash Table Size is entered as : 5Two key-value pairs are insertedG 121F 212Later Hash table is cleared Comment More infoAdvertise with us Next Article Java Program to Implement HashTables with Linear Probing M mayanktyagi1709 Follow Improve Article Tags : Java Technical Scripter Java Programs Technical Scripter 2020 Java-Collections Java-HashTable +2 More Practice Tags : JavaJava-Collections Similar Reads Java Program to Implement HashTable API The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. To implement Hashtable API f 4 min read Java Program to Implement LinkedHashMap API The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements 3 min read Java Program to Implement Hash Table Chaining with List Heads A hash table is a data structure that executes a connected array, it is a structure that maps keys to its values. It uses a hash function to calculate an index position for the keys, also called hash code. It will store key and value pair in an array of buckets, and from that bucket, the values can 4 min read Java Program to Implement Hash Tables Chaining with Doubly Linked Lists Hash Tables(similar to tables in general) provide a subset of the dynamic set operations. Usually, a set of keys are mapped with some values based on certain relations. However, there might be situations when different keys map to the same position provided by the Hash function, which leads to a col 5 min read Java Program to Implement LinkedHashSet API The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained, this class is used. When iterating through a HashSet, the order is unpredictable, while a LinkedHashSet lets us iterate through the element 4 min read Java Program to Implement Hash Tables with Double Hashing Double hashing is a technique in an open addressing scheme. and there is the ordinary hash function. In an open addressing scheme, the actual hash function is taking the ordinary hash function when its space is not empty then it will perform another hash function to get some space to insert. Double 10 min read Java Program to Implement ConcurrentHashMap API ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap a 6 min read Hashtable Implementation with equals and hashcode Method in Java To implement a hash table, we should use the hash table class, which will map keys to the values. The key or values of the hash table should be a non-null object. In order to store and retrieve data from the hash table, the non-null objects, that are used as keys must implement the hashCode() method 6 min read Java Program to Iterate LinkedHashSet Elements The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements 3 min read Java Program to Implement ConcurrentSkipListMap API ConcurrentSkipListMap API is based on the implementation of the ConcurrentNavigableMap. This map is sorted according to the natural ordering of its keys or by a Comparator provided on the map during creation time. This class implements a concurrent variant of SkipLists which makes its expected avera 10 min read Like