public class LinearProbingHashTable { private String[] keys; private String[] values; private int size; private int capacity; public LinearProbingHashTable(int capacity) { this.capacity = capacity; this.keys = new String[capacity]; this.values = new String[capacity]; this.size = 0; } private int hash(String key) { return key.length() % capacity; } public void put(String key, String value) { if (key == null || value == null) { throw new IllegalArgumentException("Key or value cannot be null."); } int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { values[index] = value; return; } index = (index + 1) % capacity; } keys[index] = key; values[index] = value; size++; } public String get(String key) { int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { return values[index]; } index = (index + 1) % capacity; } return null; } public void display() { for (int i = 0; i < capacity; i++) { if (keys[i] != null) { System.out.println("Key: " + keys[i] + ", Value: " + values[i]); } } } public static void main(String[] args) { LinearProbingHashTable hashTable = new LinearProbingHashTable(10); hashTable.put("John", "Doe"); hashTable.put("Alice", "Smith"); hashTable.put("Bob", "Johnson"); hashTable.put("Charlie", "Brown"); hashTable.display(); System.out.println("Value associated with 'John': " + hashTable.get("John")); System.out.println("Value associated with 'Alice': " + hashTable.get("Alice")); System.out.println("Value associated with 'Bob': " + hashTable.get("Bob")); System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie")); System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter