import java.math.BigInteger; import java.util.HashMap; import java.util.Random; /** * A very simple hashtable implementation. * No collision handling. * No rehashing. * The key must be an integer, the value must be a string * The table size is fixed at 4. * The implementation assumes that a collision on hashed keys is * equivalent to a collision of keys. * @author gtowell * Created: April 23, 2020 */ public class SimpleHT { /** The array actually storing the data */ private String[] backingArray; /** * Initialize the hashtable */ public SimpleHT() { backingArray = new String[4]; } /** * The compression function for the hashfunction. * Since the key must be an integer, compression is all that is * required. * @param k the integer to be compressed. * @return the compressed integer */ private int h(int k) { if (k<0) k=-k; return k%4; } /** * Add a key-value par to the hashtable * @param key the integer key * @param value the value to be stored. */ public void put(Integer key, String value) { backingArray[h(key)] = value; } /** * Get a value given a key * @param key the key whose value is to be retrieved from the hashtable * @return the value or null is the key is not in the table. */ public String get(Integer key) { return backingArray[h(key)]; } 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)); } }