1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Random;
  4.  
  5.  
  6. public class HashTable {
  7.    
  8.     class KeyValuePair {
  9.        
  10.         Object key;
  11.        
  12.         Object value;
  13.        
  14.         public KeyValuePair(Object key, Object value) {
  15.             this.key = key;
  16.             this.value = value;
  17.         }
  18.     }
  19.    
  20.     private Object[] values;
  21.  
  22.     private int capacity;
  23.    
  24.     public HashTable(int capacity) {
  25.         values = new Object[capacity];
  26.         this.capacity = capacity;
  27.     }
  28.  
  29.     private int hash(Object key) {
  30.         return Math.abs(key.hashCode()) % capacity;
  31.     }
  32.    
  33.     public void add(Object key, Object value) throws IllegalArgumentException {
  34.        
  35.         if (key == null || value == null)
  36.             throw new IllegalArgumentException("key or value is null");
  37.        
  38.         int index = hash(key);
  39.        
  40.         List<KeyValuePair> list;
  41.         if (values[index] == null) {
  42.             list = new ArrayList<KeyValuePair>();
  43.             values[index] = list;
  44.            
  45.         } else {
  46.             // collision
  47.             list = (List<KeyValuePair>) values[index];
  48.         }
  49.        
  50.         list.add(new KeyValuePair(key, value));
  51.     }
  52.    
  53.     public Object get(Object key) {
  54.         List<KeyValuePair> list = (List<KeyValuePair>) values[hash(key)];
  55.         for (KeyValuePair kvp : list) {
  56.             if (kvp.key.equals(key))
  57.                 return kvp.value;
  58.         }
  59.         return null;
  60.     }
  61.  
  62.     /**
  63.      * Test
  64.      */
  65.     public static void main(String[] args) {
  66.        
  67.         HashTable ht = new HashTable(100);
  68.        
  69.         for (int i = 1; i <= 1000; i++) {
  70.             ht.add("key" + i, "value" + i);
  71.         }
  72.        
  73.         Random random = new Random();
  74.         for (int i = 1; i <= 10; i++) {
  75.             String key = "key" + random.nextInt(1000);
  76.             System.out.println("ht.get(\"" + key + "\") = " + ht.get(key));
  77.         }  
  78.     }
  79. }