/** * A simple, and vastly overly simplistic implementation of * a Hashtable. * SO simple that it does not even use generics!!!! * @author gtowell * Created: Feb 8, 2022 */ public class SimpleHT { /** * A Non-generic key-value pair. * The key is always an integer and the value always a string */ private class Pair { // the key. Once set it cannot be changed public final Integer key; // the value public String value; //Create a key value pair. Pair(Integer ky, String val) { key = ky; value = val; } } //the array underlying this hashtable private Pair[] backingArray; /** * Initialize the array, and not much more */ public SimpleHT() { // The backing array is of length 4. This length is ties to the hashing function backingArray = new Pair[4]; } /** * The hashing function. Matched to the backing array length * @param k * @return */ private int h(int k) { return k % backingArray.length; } /** * Put a value into the hashtable. No worries about collisions. * @param key the key * @param value the value to be stored */ public void put(Integer key, String value) { backingArray[h(key)] = new Pair(key, value); } /** * Get a value from the hashtable * @param key the key * @return the value associated with the key, or null is there is no * value */ public String get(Integer key) { return backingArray[h(key)].value; } /** * Example of the use of SimpleHT * @param args NOT USED */ public static void main(String[] args) { SimpleHT sht = new SimpleHT(); for (int i=0; i<10; i++) { System.out.println("adding item with key=" + i + " value=" + String.format("%c", 'a'+i)); sht.put(i, String.format("%c", 'a'+i)); } for (int i=0; i<10; i++) System.out.println("getting key="+i+" value="+sht.get(i)); } }