Java/Collections Data Structure/HashTable Map

Материал из Java эксперт
Перейти к: навигация, поиск

A Map implemented with ArrayLists

     
// : c11:SlowMap.java
// A Map implemented with ArrayLists.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class SlowMap extends AbstractMap {
  private List keys = new ArrayList(), values = new ArrayList();
  public Object put(Object key, Object value) {
    Object result = get(key);
    if (!keys.contains(key)) {
      keys.add(key);
      values.add(value);
    } else
      values.set(keys.indexOf(key), value);
    return result;
  }
  public Object get(Object key) {
    if (!keys.contains(key))
      return null;
    return values.get(keys.indexOf(key));
  }
  public Set entrySet() {
    Set entries = new HashSet();
    Iterator ki = keys.iterator(), vi = values.iterator();
    while (ki.hasNext())
      entries.add(new MPair(ki.next(), vi.next()));
    return entries;
  }
  public String toString() {
    StringBuffer s = new StringBuffer("{");
    Iterator ki = keys.iterator(), vi = values.iterator();
    while (ki.hasNext()) {
      s.append(ki.next() + "=" + vi.next());
      if (ki.hasNext())
        s.append(", ");
    }
    s.append("}");
    return s.toString();
  }
  public static void main(String[] args) {
    SlowMap m = new SlowMap();
    m.put("Adobe", "Mountain View, CA");
    m.put("IBM", "White Plains, NY");
    m.put("Learning Tree", "Los Angeles, CA");
    m.put("Microsoft", "Redmond, WA");
    m.put("Netscape", "Mountain View, CA");
    m.put("O"Reilly", "Sebastopol, CA");
    m.put("Sun", "Mountain View, CA");
    System.out.println(m);
  }
} ///:~
class MPair implements Entry, Comparable {
  Object key, value;
  MPair(Object k, Object v) {
    key = k;
    value = v;
  }
  public Object getKey() { return key; }
  public Object getValue() { return value; }
  public Object setValue(Object v){
    Object result = value;
    value = v;
    return result;
  }
  public boolean equals(Object o) {
    return key.equals(((MPair)o).key);
  }
  public int compareTo(Object rv) {
    return ((Comparable)key).rupareTo(
      ((MPair)rv).key);
  }
} ///:~





Array Map extends AbstractMap

     
import java.io.Serializable;
import java.util.*;
public class ArrayMap extends AbstractMap
    implements Cloneable, Serializable {
  static class Entry implements Map.Entry {
    protected Object key, value;
    public Entry(Object key, Object value) {
      this.key = key;
      this.value = value;
    }
    public Object getKey() {
      return key;
    }
    public Object getValue() {
      return value;
    }
    public Object setValue(Object newValue) {
      Object oldValue = value;
      value = newValue;
      return oldValue;
    }
    public boolean equals(Object o) {
      if (!(o instanceof Map.Entry)) {
        return false;
      }
      Map.Entry e = (Map.Entry)o;
      return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
        (value==null ? e.getValue()==null : value.equals(e.getValue()));
    }
    public int hashCode() {
      int keyHash = (key==null ? 0 : key.hashCode());
      int valueHash = (value==null ? 0 : value.hashCode());
      return keyHash ^ valueHash;
    }
    public String toString() {
      return key + "=" + value;
    }
  }
  private Set entries = null;
  private ArrayList list;
  public ArrayMap() {
    list = new ArrayList();
  }
  public ArrayMap(Map map) {
    list = new ArrayList();
    putAll(map);
  }
  public ArrayMap(int initialCapacity) {
    list = new ArrayList(initialCapacity);
  }
  public Set entrySet() {
    if (entries==null) {
      entries = new AbstractSet() {
        public void clear() {
          list.clear();
        }
        public Iterator iterator() {
          return list.iterator();
        }
        public int size() {
          return list.size();
        }
      };
    }
    return entries;
  }
  public Object put(Object key, Object value) {
    int size = list.size();
    Entry entry = null;
    int i;
    if (key==null) {
      for (i=0; i<size; i++) {
        entry = (Entry)(list.get(i));
        if (entry.getKey() == null) {
          break;
        }
      }
    } else {
      for (i=0; i<size; i++) {
        entry = (Entry)(list.get(i));
        if (key.equals(entry.getKey())) {
          break;
        }
      }
    }
    Object oldValue = null;
    if (i<size) {
      oldValue = entry.getValue();
      entry.setValue(value);
    } else {
      list.add(new Entry(key, value));
    }
    return oldValue;
  }
  public Object clone() {
    return new ArrayMap(this);
  }
}





A simple Map implementation

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.util.*;
/** A simple Map implementation, implemented in terms of a
 * pair of ArrayLists just to show what a Map has to do (it would 
 * have been easier, but less informative, to subclass AbstractMap).
 * This Map implementation, like TreeSet, guarantees that the 
 * Map"s contents will be kept in ascending element order, 
 * sorted according to the natural order of the elements;
 * see Comparable. This does not (yet) allow you to specify your own
 * Comparator.
 * <p>
 * It is a requirement that all objects inserted be able to 
 * call compareTo on all other objects, i.e., they must all
 * be of the same or related classes.
 * <p>
 * Be warned that the entrySet() method is <b>not implemented</b> yet.
 */
public class MyMap implements Map {
  private ArrayList keys;
  private ArrayList values;
  public MyMap() {
    keys = new ArrayList();
    values = new ArrayList();
  }
  /** Return the number of mappings in this Map. */
  public int size() {
    return keys.size();
  }
  /** Return true if this map is empty. */
  public boolean isEmpty() {
    return size() == 0;
  }
  /** Return true if o is contained as a Key in this Map. */
  public boolean containsKey(Object o) {
    return keys.contains(o);
  }
  /** Return true if o is contained as a Value in this Map. */
  public boolean containsValue(Object o) {
    return keys.contains(o);
  }
  /** Get the object value corresponding to key k. */
  public Object get(Object k) {
    int i = keys.indexOf(k);
    if (i == -1)
      return null;
    return values.get(i);
  }
  /** Put the given pair (k, v) into this map, by maintaining "keys"
   * in sorted order.
   */
  public Object put(Object k, Object v) {
    for (int i=0; i < keys.size(); i++) {
      Object old = keys.get(i);
      /* Does the key already exist? */
      if (((Comparable)k).rupareTo(keys.get(i)) == 0) {
        keys.set(i, v);
        return old;
      }
      /* Did we just go past where to put it?
       * i.e., keep keys in sorted order.
       */
      if (((Comparable)k).rupareTo(keys.get(i)) == +1) {
        int where = i > 0 ? i -1 : 0;
        keys.add(where, k);
        values.add(where, v);
        return null;
      }
    }
    // Else it goes at the end.
    keys.add(k);
    values.add(v);
    return null;
  }
  /** Put all the pairs from oldMap into this map */
  public void putAll(java.util.Map oldMap) {
    Iterator keysIter = oldMap.keySet().iterator();
    while (keysIter.hasNext()) {
      Object k = keysIter.next();
      Object v = oldMap.get(k);
      put(k, v);
    }
  }
  public Object remove(Object k) {
    int i = keys.indexOf(k);
    if (i == -1)
      return null;
    Object old = values.get(i);
    keys.remove(i);
    values.remove(i);
    return old;
  }
  public void clear() {
    keys.clear();
    values.clear();
  }
  public java.util.Set keySet() {
    return new TreeSet(keys);
  }
  public java.util.Collection values() {
    return values;
  }
  /** The Map.Entry objects contained in the Set returned by entrySet().
   */
  private class MyMapEntry implements Map.Entry, Comparable {
    private Object key, value;
    MyMapEntry(Object k, Object v) {
      key = k;
      value = v;
    }
    public Object getKey() { return key; }
    public Object getValue() { return value; }
    public Object setValue(Object nv) {
      throw new UnsupportedOperationException("setValue");
    }
    public int compareTo(Object o2) {
      if (!(o2 instanceof MyMapEntry))
        throw new IllegalArgumentException(
          "Huh? Not a MapEntry?");
      Object otherKey = ((MyMapEntry)o2).getKey();
      return ((Comparable)key).rupareTo((Comparable)otherKey);
    }
    }
  /** The set of Map.Entry objects returned from entrySet(). */
  private class MyMapSet extends AbstractSet {
    List list;
    MyMapSet(ArrayList al) {
      list = al;
    }
    public Iterator iterator() {
      return list.iterator();
    }
    public int size() {
      return list.size();
    }
  }
  /** Returns a set view of the mappings contained in this Map.
   * Each element in the returned set is a Map.Entry.
   * NOT guaranteed fully to implement the contract of entrySet
   * declared in java.util.Map.
   */
    public java.util.Set entrySet() {
    if (keys.size() != values.size())
      throw new IllegalStateException(
        "InternalError: keys and values out of sync");
    ArrayList al = new ArrayList();
    for (int i=0; i<keys.size(); i++) {
      al.add(new MyMapEntry(keys.get(i), values.get(i)));
    }
    return new MyMapSet(al); 
  }
  public static void main(String[] argv) {
    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.
    Map map = new MyMap();
    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    map.put("Adobe", "Mountain View, CA");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("IBM", "White Plains, NY");
    map.put("Netscape", "Mountain View, CA");
    map.put("Microsoft", "Redmond, WA");
    map.put("Sun", "Mountain View, CA");
    map.put("O"Reilly", "Sebastopol, CA");
    // Two versions of the "retrieval" phase.
    // Version 1: get one pair"s value given its key
    // (presumably the key would really come from user input):
    String queryString = "O"Reilly";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String)map.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();
    // Version 2: get ALL the keys and pairs 
    // (maybe to print a report, or to save to disk)
    Iterator k = map.keySet().iterator();
    while (k.hasNext()) {
      String key = (String) k.next();
      System.out.println("Key " + key + "; Value " +
        (String) map.get(key));
    }
    // Step 3 - try out the entrySet() method.
    Set es = map.entrySet();
    System.out.println("entrySet() returns " + es.size() + " Map.Entry"s");
  }
}





Associates keys with values

     
// : c10:AssociativeArray.java
// Associates keys with values.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class AssociativeArray {
  private Object[][] pairs;
  private int index;
  public AssociativeArray(int length) {
    pairs = new Object[length][2];
  }
  public void put(Object key, Object value) {
    if (index >= pairs.length)
      throw new ArrayIndexOutOfBoundsException();
    pairs[index++] = new Object[] { key, value };
  }
  public Object get(Object key) {
    for (int i = 0; i < index; i++)
      if (key.equals(pairs[i][0]))
        return pairs[i][1];
    throw new RuntimeException("Failed to find key");
  }
  public String toString() {
    String result = "";
    for (int i = 0; i < index; i++) {
      result += pairs[i][0] + " : " + pairs[i][1];
      if (i < index - 1)
        result += "\n";
    }
    return result;
  }
  public static void main(String[] args) {
    AssociativeArray map = new AssociativeArray(6);
    map.put("sky", "blue");
    map.put("grass", "green");
    map.put("ocean", "dancing");
    map.put("tree", "tall");
    map.put("earth", "brown");
    map.put("sun", "warm");
    try {
      map.put("extra", "object"); // Past the end
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Too many objects!");
    }
    System.out.println(map);
    System.out.println(map.get("ocean"));
  }
} ///:~





Bucketized Hashtable

   
/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the "License").  You may not use this file except 
 * in compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt or 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html. 
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * HEADER in each file and include the License file at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
 * add the following below this CDDL HEADER, with the 
 * fields enclosed by brackets "[]" replaced with your 
 * own identifying information: Portions Copyright [yyyy] 
 * [name of copyright owner]
 */

import java.io.Serializable;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * This class implements bucketize hashtable, which subdivide the key collection
 * stored into several hashtables (buckets) of smaller size. This will reduce
 * the contention of hashtable.
 * @author Shing Wai Chan
 */
public class BucketizedHashtable implements Cloneable, Map, Serializable {
    private int bucketSize;
    private Hashtable[] hashtables = null;
    /**
     * Constructs a new, empty BucketizedHashtable with the specified bucket
     * size, initial capacity and load factor.
     * @param bucketSize the number of buckets used for hashing
     * @param initialCapacity the initial capacity of BucketizedHashtable
     * @param loadFactor the load factor of hashtable
     */
    public BucketizedHashtable(int bucketSize, int initialCapacity,
            float loadFactor) {
        if (bucketSize <= 0 || initialCapacity < 0) {
            throw new IllegalArgumentException();
        }
        this.bucketSize = bucketSize;
        hashtables = new Hashtable[bucketSize];
        // always round up to the nearest integer so that it has at
        // least the initialCapacity
        int initialHashtableSize = (int) Math.ceil(
                (double) initialCapacity / bucketSize);
        for (int i = 0; i < bucketSize; i++) {
            hashtables[i] = new Hashtable(initialHashtableSize, loadFactor);
        }
    }
    /**
     * Constructs a new, empty BucketizedHashtable with the specified bucket
     * size, initial capacity and default load factor 0.75.
     * @param bucketSize the number of buckets used for hashing
     * @param initialCapacity the initial capacity of hashtable
     */
    public BucketizedHashtable(int bucketSize, int initialCapacity) {
        this(bucketSize, initialCapacity, 0.75f);
    }
    /**
     * Constructs a new, empty BucketizedHashtable with the specified bucket
     * size, default initial capacity (11 * bucketSize) and default load factor
     * 0.75.
     * @param bucketSize the number of buckets used for hashing
     */
    public BucketizedHashtable(int bucketSize) {
        this(bucketSize, 11 * bucketSize, 0.75f);
    }
    /**
     * Constructs a new, empty BucketizedHashtable with the default bucket size
     * 11, default initial capacity (11 * bucketSize) and default load factor
     * 0.75.
     * @param bucketSize the number of buckets used for hashing
     */
    public BucketizedHashtable() {
        this(11, 11 * 11, 0.75f);
    }
    //-------- implementing Map --------
    /**
     * @param key a key in the hashtable
     * @return the value to which the specified key is mapped.
     */
    public Object get(Object key) {
        return hashtables[getBucketIndex(key)].get(key);
    }
    /**
     * Remove the key and its corresponding value.
     * @param key the key that needs to be removed
     * @return the value to which the key had been mapped, or <code>null</code>
     *         if the key did not have a mapping.
     */
    public Object remove(Object key) {
        return hashtables[getBucketIndex(key)].remove(key);
    }
    /**
     * Maps the specified <code>key</code> to the specified <code>value</code>
     * in this hashtable. Neither the key nor the value can be
     * <code>null</code>. <p>
     * @param key the hashtable key
     * @param value the value
     * @return the previous value of the specified key in hashtables, or
     *         <code>null</code> if it did not have one.
     */
    public Object put(Object key, Object value) {
        return hashtables[getBucketIndex(key)].put(key, value);
    }
    /**
     * @param t BucketizedHashtable or a Map with a supported operation
     * entrySet
     */
    public void putAll(Map t) {
        if (t instanceof BucketizedHashtable) {
            BucketizedHashtable bt = (BucketizedHashtable) t;
            for (int i = 0; i < bt.bucketSize; i++) {
                putAllFromMapWithEntrySet(bt.hashtables[i]);
            }
        } else {
            putAllFromMapWithEntrySet(t);
        }
    }
    /**
     * @param key possible key
     * @return true if and only if the specified object is a key in one of of
     *         the hashtables
     */
    public boolean containsKey(Object key) {
        return hashtables[getBucketIndex(key)].containsKey(key);
    }
    /**
     * @param value possible value
     * @return true if and only if the specified object is a value in one of of
     *         the hashtables
     */
    public boolean containsValue(Object value) {
        for (int i = 0; i < bucketSize; i++) {
            if (hashtables[i].containsValue(value)) {
                return true;
            }
        }
        return false;
    }
    /**
     * @return the total number of key-value mappings of all buckets
     */
    public int size() {
        int totalSize = 0;
        for (int i = 0; i < bucketSize; i++) {
            totalSize += hashtables[i].size();
        }
        return totalSize;
    }
    /**
     * @return the hash code value for this map
     */
    public int hashCode() {
        int h = 0;
        for (int i = 0; i < bucketSize; i++) {
            h += hashtables[i].hashCode();
        }
        return h;
    }
    /**
     * @return true if this map contains no key-value mappings
     */
    public boolean isEmpty() {
        for (int i = 0; i < bucketSize; i++) {
            if (!hashtables[i].isEmpty()) {
                return false;
            }
        }
        return true;
    }
    /**
     * Clears this BucketizedHashtable so that it contains no key.
     */
    public void clear() {
        for (int i = 0; i < bucketSize; i++) {
            hashtables[i].clear();
        }
    }
    /**
     * The return set is backed by the map, so changes to the map are reflected
     * in the set, and vice-versa.
     * @return a set of Map.Entry when bucketSet equal 1
     * @throws UnsupportedOperationException when bucketSize is greater one
     */
    public Set entrySet() {
        if (bucketSize == 1) {
            return hashtables[0].entrySet();
        } else {
            throw new UnsupportedOperationException();
        }
    }
    /**
     * The return set is backed by the map, so changes to the map are reflected
     * in the set, and vice-versa.
     * @return a set of keys when bucketSet equal 1
     * @throws UnsupportedOperationException when bucketSize is greater one
     */
    public Set keySet() {
        if (bucketSize == 1) {
            return hashtables[0].keySet();
        } else {
            throw new UnsupportedOperationException();
        }
    }
    /**
     * The return collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.
     * @return a collection of values when bucketSet equal 1
     * @throws UnsupportedOperationException when bucketSize is greater one
     */
    public Collection values() {
        if (bucketSize == 1) {
            return hashtables[0].values();
        } else {
            throw new UnsupportedOperationException();
        }
    }
    /**
     * Compares the specified object with this map for equality.
     * @return true if the specified object is a BucketizedHashtable with
     *         hashtables represent the same set of mappings.
     */
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (!(o instanceof BucketizedHashtable)) {
            return false;
        }
        BucketizedHashtable bt = (BucketizedHashtable) o;
        if (bt.bucketSize != bucketSize || bt.size() != size()) {
            return false;
        }
        for (int i = 0; i < bucketSize; i++) {
            if (!hashtables[i].equals(bt.hashtables[i])) {
                return false;
            }
        }
        return true;
    }
    //-------- implementing Cloneable --------
    /**
     * Creates and returns a shallow copy of this object. The keys and values
     * are not cloned.
     * @return a clone of BucketizedHashtable
     */
    public Object clone() {
        try {
            BucketizedHashtable bt = (BucketizedHashtable) super.clone();
            bt.bucketSize = bucketSize;
            bt.hashtables = new Hashtable[bucketSize];
            for (int i = 0; i < bucketSize; i++) {
                bt.hashtables[i] = (Hashtable) hashtables[i].clone();
            }
            return bt;
        } catch (CloneNotSupportedException e) {
            // this shouldn"t happen, since we are Cloneable
            throw new InternalError();
        }
    }
    //----------------
    /**
     * @return a string representation of this BucketizedHashtable
     */
    public String toString() {
        StringBuffer buf = new StringBuffer("[");  // NOI18N
        //bucketSize always >= 1 
        buf.append(hashtables[0].toString());
        for (int i = 1; i < bucketSize; i++) {
            buf.append(", "); // NOI18N
            buf.append(hashtables[i].toString());
        }
        buf.append("]"); // NOI18N
        return buf.toString();
    }
    /**
     * @param t Map with a supported entrySet operation
     */
    private void putAllFromMapWithEntrySet(Map t) {
        Iterator iter = t.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry e = (Map.Entry) iter.next();
            put(e.getKey(), e.getValue());
        }
    }
    /**
     * @param key
     * @return the bucket index for the specified key
     */
    private int getBucketIndex(Object key) {
        int index = key.hashCode() % bucketSize;
        return (index >= 0) ? index : index + bucketSize;
    }
}





Caching Hashtable

    
/*
 * CachingHashtable.java
 *
 * Created on January 13, 2005, 1:49 PM
 *
 * Copyright (C) 2005  Robert Cooper, Temple of the Screaming Penguin
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;

/**
 * This class provides a Hashtable that has a time-based limit on how long something
 * remains in the table.
 *
 * <p>There are two modes that this class can operate in: threaded and unthreaded. When
 * operating in threaded mode, it will spawn a separate thread process to clean elements
 * out of the table as they expire. When in unthreaded mode, it will check expiration
 * state as requests to the object are made.</p>
 *
 * <p>Each of these has advantages and disadvantages. As a rule, if you expect the table
 * to grow large and be around for a while, best to use the threaded mode as it will
 * help keep the static memory state lower and performance of table-wide access calls like
 * .keys() will be better. If you expect to have a small, or short lived table, unthreaded
 * will eliminate the overhead of the cleaner thread. Another consideration follows.</p>
 *
 * <p>The Time to Live value operates slightly differently between these two modes.
 * In threaded mode, TTL is both the checking bound on an item AND the sleep timer
 * between cleans of the cache. It is, therefore, possible to have a cache element
 * returned with 2 * TTL - 1 millisecond since incept. When in unthreaded mode,
 * objects are guaranteed not to have a lifespan exceeding the TTL.</p>
 *
 * <p>When no value is specified, threaded is true and TTL is 1 minute.</p>
 * @version $Rev: 86 $
 * @author 
 */
public class CachingHashtable<K, V> extends Hashtable<K,V> {
    /**
     * DOCUMENT ME!
     */
    private Cleaner cleaner;
    /**
     * DOCUMENT ME!
     */
    private Hashtable<K,CacheElement<V>> cache;
    /**
     * DOCUMENT ME!
     */
    private boolean threaded = true;
    /**
     * DOCUMENT ME!
     */
    private long ttl = 60000;
    /**
     * Creates a new CachingHashtable object.
     */
    public CachingHashtable() {
        init(threaded,ttl,0,null);
    }
    /**
     *
     */
    public CachingHashtable(boolean threaded) {
        init(threaded,ttl,0,null);
    }
    /**
     *
     */
    public CachingHashtable(long ttl) {
        init(threaded,ttl,0,null);
    }
    /**
     *
     */
    public CachingHashtable(boolean threaded,long ttl) {
        init(threaded,ttl,0,null);
    }
    /**
     *
     */
    public CachingHashtable(boolean threaded,long ttl,int initialCapacity) {
        init(threaded,ttl,initialCapacity,null);
    }
    /**
     * Creates a new CachingHashtable object.
     *
     * @param initialCapacity DOCUMENT ME!
     */
    public CachingHashtable(int initialCapacity) {
        init(threaded,ttl,initialCapacity,null);
    }
    /**
     *
     */
    public CachingHashtable(boolean threaded,int initialCapacity) {
        init(threaded,ttl,initialCapacity,null);
    }
    /**
     *
     */
    public CachingHashtable(long ttl,int initialCapacity) {
        init(threaded,ttl,initialCapacity,null);
    }
    /**
     * Creates a new CachingHashtable object.
     *
     * @param map DOCUMENT ME!
     */
    public CachingHashtable(Map<? extends K,? extends V> map) {
        init(threaded,ttl,0,map);
    }
    /**
     *
     */
    public CachingHashtable(long ttl,Map<? extends K,? extends V> map) {
        init(threaded,ttl,0,map);
    }
    /**
     *
     */
    public CachingHashtable(boolean threaded,long ttl,Map<? extends K,? extends V> map) {
        init(threaded,ttl,0,map);
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean isEmpty() {
        if(threaded) {
            return cache.isEmpty();
        } else {
            cleaner.clean();
            return cache.isEmpty();
        }
    }
    /**
     *
     * @param ttl new Time to Live value for this table
     */
    public void setTimeToLive(long ttl) {
        this.ttl = ttl;
        this.cleaner.ttl = ttl;
    }
    /**
     *
     * @return the Time to Live for elements in this table
     */
    public long getTimeToLive() {
        return this.ttl;
    }
    /**
     * DOCUMENT ME!
     *
     * @param key DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Long cacheTime(K key) {
        CacheElement ce = cache.get(key);
        if(ce == null) {
            return null;
        }
        return new Long(ce.incept);
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Map<K,Long> cacheTimes() {
        HashMap<K,Long> set = new HashMap<K,Long>();
        if(!threaded) {
            cleaner.clean();
        }
        for(K key : cache.keySet()) {
            set.put(key,new Long(cache.get(key).incept));
        }
        return set;
    }
    /**
     * DOCUMENT ME!
     */
    //begin the long march of Hashtable overrides
    public void clear() {
        cache.clear();
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Object clone() {
        CachingHashtable<K,V> o = new CachingHashtable<K,V>(threaded,ttl);
        o.cache = (Hashtable<K,CacheElement<V>>)this.cache.clone();
        return o;
    }
    /**
     * DOCUMENT ME!
     *
     * @param o DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean contains(Object o) {
        if(!threaded) {
            cleaner.clean();
        }
        for(CacheElement<V> element : cache.values()) {
            if((element.payload == o)||o.equals(element.payload)) {
                return true;
            }
        }
        return false;
    }
    /**
     * DOCUMENT ME!
     *
     * @param o DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean containsKey(Object o) {
        if(!threaded) {
            cleaner.clean();
        }
        return cache.containsKey(o);
    }
    /**
     * DOCUMENT ME!
     *
     * @param o DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean containsValue(Object o) {
        return contains(o);
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Enumeration<V> elements() {
        return new CacheEnumeration(super.elements());
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Set<Map.Entry<K,V>> entrySet() {
        HashSet set = new HashSet();
        if(!threaded) {
            cleaner.clean();
        }
        for(K key : cache.keySet()) {
            set.add(new MapEntry(key,cache.get(key)));
        }
        return set;
    }
    /**
     * DOCUMENT ME!
     *
     * @param o DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean equals(Object o) {
        if(o instanceof CachingHashtable&&((CachingHashtable)o).cache.equals(this.cache)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * DOCUMENT ME!
     */
    public void finalize() {
        cleaner.shutdown();
    }
    /**
     * DOCUMENT ME!
     *
     * @param o DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public V get(Object o) {
        K key = (K)o;
        if(threaded) {
            if(cache.get(key) != null) {
                return cache.get(key).payload;
            } else {
                return null;
            }
        } else {
            CacheElement<V> ce = cache.get(key);
            if((ce == null)||((System.currentTimeMillis() - ce.incept) >= ttl)) {
                cache.remove(key);
                return null;
            } else {
                return ce.payload;
            }
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public int hashCode() {
        return cache.hashCode();
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Set<K> keySet() {
        if(threaded) {
            return cache.keySet();
        } else {
            cleaner.clean();
            return cache.keySet();
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Enumeration<K> keys() {
        if(threaded) {
            return cache.keys();
        } else {
            cleaner.clean();
            return cache.keys();
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @param key DOCUMENT ME!
     * @param value DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public V put(K key,V value) {
        CacheElement<V> element = new CacheElement<V>(value);
        CacheElement<V> old = cache.put(key,element);
        if(old != null) {
            return old.payload;
        } else {
            return null;
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @param map DOCUMENT ME!
     */
    public void putAll(Map<? extends K,? extends V> map) {
        for(K key : map.keySet()) {
            cache.put(key,new CacheElement<V>(map.get(key)));
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @param o DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public V remove(Object o) {
        K key = (K)o;
        if(threaded) {
            return cache.remove(key).payload;
        } else {
            V value = this.get(key);
            cache.remove(key);
            return value;
        }
    }
    /** Stops processing.
     */
    public void shutdown() {
        this.threaded = false;
        cleaner.shutdown();
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public int size() {
        if(threaded) {
            return cache.size();
        } else {
            cleaner.clean();
            return cache.size();
        }
    }
    /** Starts the processing.
     */
    public void startup() {
        this.threaded = true;
        cleaner.startup();
    }
    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Collection<V> values() {
        if(!threaded) {
            cleaner.clean();
        }
        ArrayList<V> values = new ArrayList<V>(cache.size());
        for(CacheElement<V> element : cache.values())
            values.add(element.payload);
        return values;
    }
    /**
     * DOCUMENT ME!
     *
     * @param threaded DOCUMENT ME!
     * @param ttl DOCUMENT ME!
     * @param initialCapacity DOCUMENT ME!
     * @param map DOCUMENT ME!
     */
    private void init(boolean threaded,long ttl,int initialCapacity,Map<? extends K,? extends V> map) {
        if(map != null) {
            initialCapacity = map.size();
        }
        cache = new Hashtable<K,CacheElement<V>>(initialCapacity);
        this.ttl = ttl;
        this.threaded = threaded;
        if(map != null) {
            putAll(map);
        }
        this.cleaner = new Cleaner(ttl,cache);
        if(threaded) {
            cleaner.startup();
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @author $author$
     * @version $Revision: 1.4 $
     */
    private static class CacheElement<V> {
        /**
         * DOCUMENT ME!
         */
        public V payload;
        /**
         * DOCUMENT ME!
         */
        public long incept = System.currentTimeMillis();
        /**
         * Creates a new CacheElement object.
         *
         * @param payload DOCUMENT ME!
         */
        public CacheElement(V payload) {
            this.payload = payload;
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @author $author$
     * @version $Revision: 1.4 $
     */
    private static class CacheEnumeration<V> implements Enumeration<V> {
        /**
         * DOCUMENT ME!
         */
        Enumeration<CacheElement<V>> enu;
        /**
         * Creates a new CacheEnumeration object.
         *
         * @param enu DOCUMENT ME!
         */
        CacheEnumeration(Enumeration<CacheElement<V>> enu) {
            this.enu = enu;
        }
        /**
         * DOCUMENT ME!
         *
         * @return DOCUMENT ME!
         */
        public boolean hasMoreElements() {
            return enu.hasMoreElements();
        }
        /**
         * DOCUMENT ME!
         *
         * @return DOCUMENT ME!
         */
        public V nextElement() {
            return enu.nextElement().payload;
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @author $author$
     * @version $Revision: 1.4 $
     */
    private class Cleaner extends Thread {
        /**
         * DOCUMENT ME!
         */
        private Hashtable<K,? extends CacheElement> cache;
        /**
         * DOCUMENT ME!
         */
        private boolean running = false;
        /**
         * DOCUMENT ME!
         */
        private long ttl;
        /**
         * Creates a new Cleaner object.
         *
         * @param ttl DOCUMENT ME!
         * @param cache DOCUMENT ME!
         */
        Cleaner(long ttl,Hashtable<K,? extends CacheElement> cache) {
            this.ttl = ttl;
            this.cache = cache;
            this.setDaemon(true);
        }
        /**
         * DOCUMENT ME!
         *
         * @return DOCUMENT ME!
         */
        public boolean isRunning() {
            return running;
        }
        /**
         * DOCUMENT ME!
         */
        public void clean() {
            ArrayList<K> toRemove = new ArrayList<K>();
            for(K key : cache.keySet()) {
                CachingHashtable.CacheElement element = cache.get(key);
                if((System.currentTimeMillis() - element.incept) >= ttl) {
                    toRemove.add(key);
                }
            }
            for(K key : toRemove) {
                cache.remove(key);
            }
        }
        /**
         * DOCUMENT ME!
         */
        public void run() {
            while(running) {
                clean();
                try {
                    Thread.sleep(ttl);
                } catch(InterruptedException e) {
                }
            }
        }
        /**
         * DOCUMENT ME!
         */
        public void shutdown() {
            this.running = false;
        }
        /**
         * DOCUMENT ME!
         */
        public void startup() {
            this.running = true;
            super.start();
        }
    }
    /**
     * DOCUMENT ME!
     *
     * @author $author$
     * @version $Revision: 1.4 $
     */
    private static class MapEntry<K,V> implements Map.Entry {
        /**
         * DOCUMENT ME!
         */
        CacheElement<V> element;
        /**
         * DOCUMENT ME!
         */
        K key;
        /**
         * Creates a new MapEntry object.
         *
         * @param key DOCUMENT ME!
         * @param element DOCUMENT ME!
         */
        MapEntry(K key,CacheElement<V> element) {
            this.key = key;
            this.element = element;
        }
        /**
         * DOCUMENT ME!
         *
         * @return DOCUMENT ME!
         */
        public Object getKey() {
            return key;
        }
        /**
         * DOCUMENT ME!
         *
         * @param obj DOCUMENT ME!
         *
         * @return DOCUMENT ME!
         */
        public Object setValue(Object obj) {
            return element.payload = (V)obj;
        }
        /**
         * DOCUMENT ME!
         *
         * @return DOCUMENT ME!
         */
        public Object getValue() {
            return element.payload;
        }
    }
}





Check if a particular key exists in Java Hashtable

     
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    boolean blnExists = ht.containsKey("2");
    System.out.println("2 exists in Hashtable ? : " + blnExists);
  }
}





Check if a particular value exists in Java Hashtable

     
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    boolean blnExists = ht.contains("Two");
    System.out.println("Two exists in Hashtable ? : " + blnExists);
  }
}





Custom hash table based on customized array

   
/*
 * 
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights 
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:  
 *       "This product includes software developed by the 
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Jakarta Element Construction Set", 
 *    "Jakarta ECS" , and "Apache Software Foundation" must not be used 
 *    to endorse or promote products derived
 *    from this software without prior written permission. For written 
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Jakarta Element Construction Set" nor "Jakarta ECS" nor may "Apache" 
 *    appear in their names without prior written permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */
import java.util.Enumeration;
public class Hash implements java.io.Serializable {
  private Array keys = new Array();
  private Array elements = new Array();
  public Hash() {
  }
  public void setSize(int newSize) {
    keys.setSize(newSize);
    elements.setSize(newSize);
  }
  public void setGrow(int growBy) {
    keys.setGrow(growBy);
    elements.setGrow(growBy);
  }
  public synchronized void put(String key, Object element) {
    try {
      if (containsKey(key)) {
        elements.add(keys.location(key), element);
      } else {
        keys.add(key);
        elements.add(element);
      }
    } catch (NoSuchObjectException nsoe) {
    }
  }
  public synchronized void remove(String key) {
    try {
      if (containsKey(key)) {
        elements.remove(keys.location(key));
        elements.remove(elements.location(key));
      }
    } catch (NoSuchObjectException nsoe) {
    }
  }
  public int size() {
    return keys.getCurrentSize();
  }
  public boolean contains(Object element) {
    try {
      elements.location(element);
      return (true);
    } catch (NoSuchObjectException noSuchObject) {
      return false;
    }
  }
  public Enumeration keys() {
    return keys;
  }
  public boolean containsKey(String key) {
    try {
      keys.location(key);
    } catch (NoSuchObjectException noSuchObject) {
      return false;
    }
    return (true);
  }
  public Enumeration elements() {
    return elements;
  }
  public Object get(String key) {
    try {
      if (containsKey(key))
        return (elements.get(keys.location(key)));
    } catch (NoSuchObjectException nsoe) {
    }
    return null;
  }
}
class Array implements java.util.Enumeration, java.io.Serializable {
  private int current = 0;
  private int size = 10;
  private int grow = 2;
  private int place = 0;
  private Object[] elements = null;
  private Object[] tmpElements = null;
  public Array() {
    init();
  }
  public Array(int size) {
    setSize(size);
    init();
  }
  public Array(int size, int grow) {
    setSize(size);
    setGrow(grow);
    init();
  }
  private void init() {
    elements = new Object[size];
  }
  public Object nextElement() throws java.util.NoSuchElementException {
    if (elements[place] != null && place != current) {
      place++;
      return elements[place - 1];
    } else {
      place = 0;
      throw new java.util.NoSuchElementException();
    }
  }
  public boolean hasMoreElements() {
    if (place < elements.length && current != place)
      return true;
    return false;
  }
  public void setSize(int size) {
    this.size = size;
  }
  public int getCurrentSize() {
    return current;
  }
  public void rehash() {
    tmpElements = new Object[size];
    int count = 0;
    for (int x = 0; x < elements.length; x++) {
      if (elements[x] != null) {
        tmpElements[count] = elements[x];
        count++;
      }
    }
    elements = (Object[]) tmpElements.clone();
    tmpElements = null;
    current = count;
  }
  public void setGrow(int grow) {
    this.grow = grow;
  }
  public void grow() {
    size = size += (size / grow);
    rehash();
  }
  public void add(Object o) {
    if (current == elements.length)
      grow();
    try {
      elements[current] = o;
      current++;
    } catch (java.lang.ArrayStoreException ase) {
    }
  }
  public void add(int location, Object o) {
    try {
      elements[location] = o;
    } catch (java.lang.ArrayStoreException ase) {
    }
  }
  public void remove(int location) {
    elements[location] = null;
  }
  public int location(Object o) throws NoSuchObjectException {
    int loc = -1;
    for (int x = 0; x < elements.length; x++) {
      if ((elements[x] != null && elements[x] == o)
          || (elements[x] != null && elements[x].equals(o))) {
        loc = x;
        break;
      }
    }
    if (loc == -1)
      throw new NoSuchObjectException();
    return (loc);
  }
  public Object get(int location) {
    return elements[location];
  }
  public java.util.Enumeration elements() {
    return this;
  }
}
class NoSuchObjectException extends Exception {
  public NoSuchObjectException() {
    super("No such object found.");
  }
}





Demonstrate the HashMap class, and an Iterator

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * Demonstrate the HashMap class, and an Iterator.
 * 
 * @see HashTableDemo, for the older Hashtable.
 */
public class MapEntrySetDemo {
  public static void main(String[] argv) {
    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.
    Map map = new HashMap();
    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    map.put("Adobe", "Mountain View, CA");
    map.put("IBM", "White Plains, NY");
    map.put("Learning Tree", "Los Angeles, CA");
    map.put("Microsoft", "Redmond, WA");
    map.put("Netscape", "Mountain View, CA");
    map.put("O"Reilly", "Sebastopol, CA");
    map.put("Sun", "Mountain View, CA");
    // List the entries using entrySet()
    Set entries = map.entrySet();
    Iterator it = entries.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
  }
}





Demonstrate the Hashtable class, and an Enumeration

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.util.Enumeration;
import java.util.Hashtable;
/**
 * Demonstrate the Hashtable class, and an Enumeration.
 * 
 * @see HashMapDemo, for the newer HashMap class.
 */
public class HashtableDemo {
  public static void main(String[] argv) {
    // Construct and load the hash. This simulates loading a
    // database or reading from a file, or wherever the data is.
    Hashtable h = new Hashtable();
    // The hash maps from company name to address.
    // In real life this might map to an Address object...
    h.put("Adobe", "Mountain View, CA");
    h.put("IBM", "White Plains, NY");
    h.put("Learning Tree", "Los Angeles, CA");
    h.put("Microsoft", "Redmond, WA");
    h.put("Netscape", "Mountain View, CA");
    h.put("O"Reilly", "Sebastopol, CA");
    h.put("Sun", "Mountain View, CA");
    // Two versions of the "retrieval" phase.
    // Version 1: get one pair"s value given its key
    // (presumably the key would really come from user input):
    String queryString = "O"Reilly";
    System.out.println("You asked about " + queryString + ".");
    String resultString = (String) h.get(queryString);
    System.out.println("They are located in: " + resultString);
    System.out.println();
    // Version 2: get ALL the keys and pairs
    // (maybe to print a report, or to save to disk)
    Enumeration k = h.keys();
    while (k.hasMoreElements()) {
      String key = (String) k.nextElement();
      System.out.println("Key " + key + "; Value " + (String) h.get(key));
    }
  }
}





Demonstrating the WeakHashMap

     
import java.util.Map;
import java.util.WeakHashMap;
public class Weak {
  public static void main(String args[]) {
    final Map map = new WeakHashMap();
    map.put(new String("jexp"), "www.jexp.ru");
    Runnable runner = new Runnable() {
      public void run() {
        while (map.containsKey("jexp")) {
          try {
            Thread.sleep(500);
          } catch (InterruptedException ignored) {
          }
          System.out.println("Waiting");
          System.gc();
        }
      }
    };
    Thread t = new Thread(runner);
    t.start();
    System.out.println("Main waiting");
    try {
      t.join();
    } catch (InterruptedException ignored) {
    }
  }
}





Get Collection of Values from Java Hashtable

     
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String,String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    Collection c = ht.values();
    Iterator itr = c.iterator();
    while (itr.hasNext()){
      System.out.println(itr.next());
    }
    c.remove("One");
    Enumeration e = ht.elements();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());
    }
  }
}





Get Set view of Keys from Java Hashtable

     

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class Main {
  public static void main(String[] args) {
    Hashtable<String,String> ht = new Hashtable<String,String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    Set st = ht.keySet();
    Iterator itr = st.iterator();
    while (itr.hasNext()){
      System.out.println(itr.next());
    }
    st.remove("2");
    Enumeration e = ht.keys();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());      
    }
  }
}
/*
3
2
1
3
1
*/





Get Size of Java Hashtable

     
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String,String> ht = new Hashtable<String,String>();
    System.out.println("Size of Hashtable : " + ht.size());
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    System.out.println(ht.size());
    Object obj = ht.remove("2");
    System.out.println(ht.size());
  }
}





HashMap<String, Double>

      
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
class HashMapDemo {
  public static void main(String args[]) {
    HashMap<String, Double> hm = new HashMap<String, Double>();
    hm.put("A", new Double(3.34));
    hm.put("B", new Double(1.22));
    hm.put("C", new Double(1.00));
    hm.put("D", new Double(9.22));
    hm.put("E", new Double(-19.08));
    Set<Map.Entry<String, Double>> set = hm.entrySet();
    for (Map.Entry<String, Double> me : set) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }
    double balance = hm.get("A");
    hm.put("A", balance + 1000);
    System.out.println(hm.get("A"));
  }
}





Hashtable that supports mostly-concurrent reading, but exclusive writing.

    
/*   Copyright 2004 The Apache Software Foundation
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/*
  File: ConcurrentReaderHashMap
  Written by Doug Lea. Adapted and released, under explicit
  permission, from JDK1.2 HashMap.java and Hashtable.java which
  carries the following copyright:
     * Copyright 1997 by Sun Microsystems, Inc.,
     * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
     * All rights reserved.
     *
     * This software is the confidential and proprietary information
     * of Sun Microsystems, Inc. ("Confidential Information").  You
     * shall not disclose such Confidential Information and shall use
     * it only in accordance with the terms of the license agreement
     * you entered into with Sun.
  History:
  Date       Who                What
  28oct1999  dl               Created
  14dec1999  dl               jmm snapshot
  19apr2000  dl               use barrierLock
  12jan2001  dl               public release
  17nov2001  dl               Minor tunings
  20may2002  dl               BarrierLock can now be serialized.
  09dec2002  dl               Fix interference checks.
*/
//package EDU.oswego.cs.dl.util.concurrent;
// Revised from xml beans
import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

/**
 * A version of Hashtable that supports mostly-concurrent reading, but
 * exclusive writing.  Because reads are not limited to periods
 * without writes, a concurrent reader policy is weaker than a classic
 * reader/output policy, but is generally faster and allows more
 * concurrency. This class is a good choice especially for tables that
 * are mainly created by one thread during the start-up phase of a
 * program, and from then on, are mainly read (with perhaps occasional
 * additions or removals) in many threads.  If you also need concurrency
 * among writes, consider instead using ConcurrentHashMap.
 * <p>
 *
 * Successful retrievals using get(key) and containsKey(key) usually
 * run without locking. Unsuccessful ones (i.e., when the key is not
 * present) do involve brief synchronization (locking).  Also, the
 * size and isEmpty methods are always synchronized.
 *
 * <p> Because retrieval operations can ordinarily overlap with
 * writing operations (i.e., put, remove, and their derivatives),
 * retrievals can only be guaranteed to return the results of the most
 * recently <em>completed</em> operations holding upon their
 * onset. Retrieval operations may or may not return results
 * reflecting in-progress writing operations.  However, the retrieval
 * operations do always return consistent results -- either those
 * holding before any single modification or after it, but never a
 * nonsense result.  For aggregate operations such as putAll and
 * clear, concurrent reads may reflect insertion or removal of only
 * some entries. In those rare contexts in which you use a hash table
 * to synchronize operations across threads (for example, to prevent
 * reads until after clears), you should either encase operations
 * in synchronized blocks, or instead use java.util.Hashtable.
 *
 * <p>
 *
 * This class also supports optional guaranteed
 * exclusive reads, simply by surrounding a call within a synchronized
 * block, as in <br> 
 * <code>ConcurrentReaderHashMap t; ... Object v; <br>
 * synchronized(t) { v = t.get(k); } </code> <br>
 *
 * But this is not usually necessary in practice. For
 * example, it is generally inefficient to write:
 *
 * <pre>
 *   ConcurrentReaderHashMap t; ...            // Inefficient version
 *   Object key; ...
 *   Object value; ...
 *   synchronized(t) { 
 *     if (!t.containsKey(key))
 *       t.put(key, value);
 *       // other code if not previously present
 *     }
 *     else {
 *       // other code if it was previously present
 *     }
 *   }
 *</pre>
 * Instead, if the values are intended to be the same in each case, just take advantage of the fact that put returns
 * null if the key was not previously present:
 * <pre>
 *   ConcurrentReaderHashMap t; ...                // Use this instead
 *   Object key; ...
 *   Object value; ...
 *   Object oldValue = t.put(key, value);
 *   if (oldValue == null) {
 *     // other code if not previously present
 *   }
 *   else {
 *     // other code if it was previously present
 *   }
 *</pre>
 * <p>
 *
 * Iterators and Enumerations (i.e., those returned by
 * keySet().iterator(), entrySet().iterator(), values().iterator(),
 * keys(), and elements()) return elements reflecting the state of the
 * hash table at some point at or since the creation of the
 * iterator/enumeration.  They will return at most one instance of
 * each element (via next()/nextElement()), but might or might not
 * reflect puts and removes that have been processed since they were
 * created.  They do <em>not</em> throw ConcurrentModificationException.
 * However, these iterators are designed to be used by only one
 * thread at a time. Sharing an iterator across multiple threads may
 * lead to unpredictable results if the table is being concurrently
 * modified.  Again, you can ensure interference-free iteration by
 * enclosing the iteration in a synchronized block.  <p>
 *
 * This class may be used as a direct replacement for any use of
 * java.util.Hashtable that does not depend on readers being blocked
 * during updates. Like Hashtable but unlike java.util.HashMap,
 * this class does NOT allow <tt>null</tt> to be used as a key or
 * value.  This class is also typically faster than ConcurrentHashMap
 * when there is usually only one thread updating the table, but 
 * possibly many retrieving values from it.
 * <p>
 *
 * Implementation note: A slightly faster implementation of
 * this class will be possible once planned Java Memory Model
 * revisions are in place.
 *
 * <p>[]
 **/

public class ConcurrentReaderHashMap 
  extends AbstractMap 
  implements Map, Cloneable, Serializable {

  /*
    The basic strategy is an optimistic-style scheme based on
    the guarantee that the hash table and its lists are always
    kept in a consistent enough state to be read without locking:
    * Read operations first proceed without locking, by traversing the
       apparently correct list of the apparently correct bin. If an
       entry is found, but not invalidated (value field null), it is
       returned. If not found, operations must recheck (after a memory
       barrier) to make sure they are using both the right list and
       the right table (which can change under resizes). If
       invalidated, reads must acquire main update lock to wait out
       the update, and then re-traverse.
    * All list additions are at the front of each bin, making it easy
       to check changes, and also fast to traverse.  Entry next
       pointers are never assigned. Remove() builds new nodes when
       necessary to preserve this.
    * Remove() (also clear()) invalidates removed nodes to alert read
       operations that they must wait out the full modifications.
 
  */
  /** A Serializable class for barrier lock **/
  protected static class BarrierLock implements java.io.Serializable { }
  /**
   * Lock used only for its memory effects.
   **/
  protected final BarrierLock barrierLock = new BarrierLock();
  /**
   * field written to only to guarantee lock ordering.
   **/
  protected transient Object lastWrite;
  /**
   * Force a memory synchronization that will cause
   * all readers to see table. Call only when already
   * holding main synch lock.
   **/
  protected final void recordModification(Object x) { 
    synchronized(barrierLock) {
      lastWrite = x;
    }
  }
  /**
   * Get ref to table; the reference and the cells it
   * accesses will be at least as fresh as from last
   * use of barrierLock
   **/
  protected final Entry[] getTableForReading() { 
    synchronized(barrierLock) {
      return table; 
    }
  }

  /**
   * The default initial number of table slots for this table (32).
   * Used when not otherwise specified in constructor.
   **/
  public static int DEFAULT_INITIAL_CAPACITY = 32; 

  /**
   * The minimum capacity, used if a lower value is implicitly specified
   * by either of the constructors with arguments.  
   * MUST be a power of two.
   */
  private static final int MINIMUM_CAPACITY = 4;
  
  /**
   * The maximum capacity, used if a higher value is implicitly specified
   * by either of the constructors with arguments.
   * MUST be a power of two <= 1<<30.
   */
  private static final int MAXIMUM_CAPACITY = 1 << 30;
  
  /**
   * The default load factor for this table (1.0).
   * Used when not otherwise specified in constructor.
   **/
  public static final float DEFAULT_LOAD_FACTOR = 0.75f; 

  /**
   * The hash table data.
   */
  protected transient Entry[] table;
  /**
   * The total number of mappings in the hash table.
   */
  protected transient int count;
  /**
   * The table is rehashed when its size exceeds this threshold.  (The
   * value of this field is always (int)(capacity * loadFactor).)
   *
   * @serial
   */
  protected int threshold;
  /**
   * The load factor for the hash table.
   *
   * @serial
   */
  protected float loadFactor;
  /**
   * Returns the appropriate capacity (power of two) for the specified 
   * initial capacity argument.
   */
  private int p2capacity(int initialCapacity) {
    int cap = initialCapacity;
    
    // Compute the appropriate capacity
    int result;
    if (cap > MAXIMUM_CAPACITY || cap < 0) {
      result = MAXIMUM_CAPACITY;
    } else {
      result = MINIMUM_CAPACITY;
      while (result < cap)
        result <<= 1;
    }
    return result;
  }
  /**
   * Return hash code for Object x. Since we are using power-of-two
   * tables, it is worth the effort to improve hashcode via
   * the same multiplicative scheme as used in IdentityHashMap.
   */
  private static int hash(Object x) {
    int h = x.hashCode();
    // Multiply by 127 (quickly, via shifts), and mix in some high
    // bits to help guard against bunching of codes that are
    // consecutive or equally spaced.
    return ((h << 7) - h + (h >>> 9) + (h >>> 17));
  }
  /** 
   * Check for equality of non-null references x and y. 
   **/
  protected boolean eq(Object x, Object y) {
    return x == y || x.equals(y);
  }
  /**
   * Constructs a new, empty map with the specified initial 
   * capacity and the specified load factor. 
   *
   * @param initialCapacity the initial capacity
   *  The actual initial capacity is rounded to the nearest power of two.
   * @param loadFactor  the load factor of the ConcurrentReaderHashMap
   * @throws IllegalArgumentException  if the initial maximum number 
   *               of elements is less
   *               than zero, or if the load factor is nonpositive.
   */
  public ConcurrentReaderHashMap(int initialCapacity, float loadFactor) {
    if (loadFactor <= 0)
      throw new IllegalArgumentException("Illegal Load factor: "+
                                         loadFactor);
    this.loadFactor = loadFactor;
    int cap = p2capacity(initialCapacity);
    table = new Entry[cap];
    threshold = (int)(cap * loadFactor);
  }
  /**
   * Constructs a new, empty map with the specified initial 
   * capacity and default load factor.
   *
   * @param   initialCapacity   the initial capacity of the 
   *                            ConcurrentReaderHashMap.
   * @throws    IllegalArgumentException if the initial maximum number 
   *              of elements is less
   *              than zero.
   */
  public ConcurrentReaderHashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
  }
  /**
   * Constructs a new, empty map with a default initial capacity
   * and load factor.
   */
  public ConcurrentReaderHashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
  }
  /**
   * Constructs a new map with the same mappings as the given map.  The
   * map is created with a capacity of twice the number of mappings in
   * the given map or 16 (whichever is greater), and a default load factor.
   */
  public ConcurrentReaderHashMap(Map t) {
        this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1, 16),
             DEFAULT_LOAD_FACTOR);
    putAll(t);
  }
  /**
   * Returns the number of key-value mappings in this map.
   *
   * @return the number of key-value mappings in this map.
   */
  public synchronized int size() {
    return count;
  }
  /**
   * Returns <tt>true</tt> if this map contains no key-value mappings.
   *
   * @return <tt>true</tt> if this map contains no key-value mappings.
   */
  public synchronized boolean isEmpty() {
    return count == 0;
  }
  

  /**
   * Returns the value to which the specified key is mapped in this table.
   *
   * @param   key   a key in the table.
   * @return  the value to which the key is mapped in this table;
   *          <code>null</code> if the key is not mapped to any value in
   *          this table.
   * @exception  NullPointerException  if the key is
   *               <code>null</code>.
   * @see     #put(Object, Object)
   */
  
  public Object get(Object key) {
    // throw null pointer exception if key null
    int hash = hash(key);
    /* 
       Start off at the apparently correct bin.  If entry is found, we
       need to check after a barrier anyway.  If not found, we need a
       barrier to check if we are actually in right bin. So either
       way, we encounter only one barrier unless we need to retry.
       And we only need to fully synchronize if there have been
       concurrent modifications.
    */
    Entry[] tab = table;
    int index = hash & (tab.length - 1);
    Entry first = tab[index];
    Entry e = first;
    for (;;) {
      if (e == null) {
        // If key apparently not there, check to
        // make sure this was a valid read
        Entry[] reread = getTableForReading();
        if (tab == reread && first == tab[index])
          return null;
        else {
          // Wrong list -- must restart traversal at new first
          tab = reread;
          e = first = tab[index = hash & (tab.length-1)];
        }
      }
      else if (e.hash == hash && eq(key, e.key)) {
        Object value = e.value;
        if (value != null) 
          return value;
        // Entry was invalidated during deletion. But it could
        // have been re-inserted, so we must retraverse.
        // To avoid useless contention, get lock to wait out modifications
        // before retraversing.
        synchronized(this) {
          tab = table;
        }
        e = first = tab[index = hash & (tab.length-1)];
      }
      else
        e = e.next;
    }
  }

  /**
   * Tests if the specified object is a key in this table.
   * 
   * @param   key   possible key.
   * @return  <code>true</code> if and only if the specified object 
   *          is a key in this table, as determined by the 
   *          <tt>equals</tt> method; <code>false</code> otherwise.
   * @exception  NullPointerException  if the key is
   *               <code>null</code>.
   * @see     #contains(Object)
   */

  public boolean containsKey(Object key) {
    return get(key) != null;
  }
  /**
   * Maps the specified <code>key</code> to the specified 
   * <code>value</code> in this table. Neither the key nor the 
   * value can be <code>null</code>. <p>
   *
   * The value can be retrieved by calling the <code>get</code> method 
   * with a key that is equal to the original key. 
   *
   * @param      key     the table key.
   * @param      value   the value.
   * @return     the previous value of the specified key in this table,
   *             or <code>null</code> if it did not have one.
   * @exception  NullPointerException  if the key or value is
   *               <code>null</code>.
   * @see     Object#equals(Object)
   * @see     #get(Object)
   */
  public Object put(Object key, Object value) {
    if (value == null) 
      throw new NullPointerException();
    
    int hash = hash(key);
    Entry[] tab = table;
    int index = hash & (tab.length-1);
    Entry first = tab[index];
    Entry e;
    for (e = first; e != null; e = e.next)
      if (e.hash == hash && eq(key, e.key))
        break;
    synchronized(this) {
      if (tab == table) {
        if (e == null) {
          //  make sure we are adding to correct list
          if (first == tab[index]) {
            //  Add to front of list
            Entry newEntry = new Entry(hash, key, value, first);
            tab[index] = newEntry;
            if (++count >= threshold) rehash();
            else recordModification(newEntry);
            return null;
          }
        }
        else {
          Object oldValue = e.value; 
          if (first == tab[index] && oldValue != null) {
            e.value = value;
            return oldValue;
          }
        }
      }
      
      // retry if wrong list or lost race against concurrent remove
      return sput(key, value, hash);
    }
  }

  /**
   * Continuation of put(), called only when synch lock is
   * held and interference has been detected.
   **/
  protected Object sput(Object key, Object value, int hash) { 
    Entry[] tab = table;
    int index = hash & (tab.length-1);
    Entry first = tab[index];
    Entry e = first;
    for (;;) {
      if (e == null) {
        Entry newEntry = new Entry(hash, key, value, first);
        tab[index] = newEntry;
        if (++count >= threshold) rehash();
        else recordModification(newEntry);
        return null;
      }
      else if (e.hash == hash && eq(key, e.key)) {
        Object oldValue = e.value; 
        e.value = value;
        return oldValue;
      }
      else
        e = e.next;
    }
  }

  /**
   * Rehashes the contents of this map into a new table
   * with a larger capacity. This method is called automatically when the
   * number of keys in this map exceeds its capacity and load factor.
   */
  protected void rehash() { 
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity >= MAXIMUM_CAPACITY) {
      threshold = Integer.MAX_VALUE; // avoid retriggering
      return;
    }
    int newCapacity = oldCapacity << 1;
    int mask = newCapacity - 1;
    threshold = (int)(newCapacity * loadFactor);
    Entry[] newTable = new Entry[newCapacity];
    /*
     * Reclassify nodes in each list to new Map.  Because we are
     * using power-of-two expansion, the elements from each bin
     * must either stay at same index, or move to
     * oldCapacity+index. We also eliminate unnecessary node
     * creation by catching cases where old nodes can be reused
     * because their next fields won"t change. Statistically, at
     * the default threshhold, only about one-sixth of them need
     * cloning. (The nodes they replace will be garbage
     * collectable as soon as they are no longer referenced by any
     * reader thread that may be in the midst of traversing table
     * right now.)
     */
    
    for (int i = 0; i < oldCapacity ; i++) {
      // We need to guarantee that any existing reads of old Map can
      //  proceed. So we cannot yet null out each bin.  
      Entry e = oldTable[i];
      
      if (e != null) {
        int idx = e.hash & mask;
        Entry next = e.next;
        
        //  Single node on list
        if (next == null) 
          newTable[idx] = e;
        
        else {    
          // Reuse trailing consecutive sequence of all same bit
          Entry lastRun = e;
          int lastIdx = idx;
          for (Entry last = next; last != null; last = last.next) {
            int k = last.hash & mask;
            if (k != lastIdx) {
              lastIdx = k;
              lastRun = last;
            }
          }
          newTable[lastIdx] = lastRun;
          
          // Clone all remaining nodes
          for (Entry p = e; p != lastRun; p = p.next) {
            int k = p.hash & mask;
            newTable[k] = new Entry(p.hash, p.key, 
                                    p.value, newTable[k]);
          }
        }
      }
    }
    table = newTable;
    recordModification(newTable);
  }
  /**
   * Removes the key (and its corresponding value) from this 
   * table. This method does nothing if the key is not in the table.
   *
   * @param   key   the key that needs to be removed.
   * @return  the value to which the key had been mapped in this table,
   *          or <code>null</code> if the key did not have a mapping.
   * @exception  NullPointerException  if the key is
   *               <code>null</code>.
   */
  public Object remove(Object key) {
    /*
      Find the entry, then 
        1. Set value field to null, to force get() to retry
        2. Rebuild the list without this entry.
           All entries following removed node can stay in list, but
           all preceeding ones need to be cloned.  Traversals rely
           on this strategy to ensure that elements will not be
          repeated during iteration.
    */
          
    int hash = hash(key);
    Entry[] tab = table;
    int index = hash & (tab.length-1);
    Entry first = tab[index];
    Entry e = first;
      
    for (e = first; e != null; e = e.next) 
      if (e.hash == hash && eq(key, e.key)) 
        break;

    synchronized(this) {
      if (tab == table) {
        if (e == null) {
          if (first == tab[index])
            return null;
        }
        else {
          Object oldValue = e.value;
          if (first == tab[index] && oldValue != null) {
            e.value = null;
            count--;
            
            Entry head = e.next;
            for (Entry p = first; p != e; p = p.next) 
              head = new Entry(p.hash, p.key, p.value, head);
            
            tab[index] = head;
            recordModification(head);
            return oldValue;
          }
        }
      }
    
      // Wrong list or interference
      return sremove(key, hash);
    }
  }
  /**
   * Continuation of remove(), called only when synch lock is
   * held and interference has been detected.
   **/
  protected Object sremove(Object key, int hash) {
    Entry[] tab = table;
    int index = hash & (tab.length-1);
    Entry first = tab[index];
      
    for (Entry e = first; e != null; e = e.next) {
      if (e.hash == hash && eq(key, e.key)) {
        Object oldValue = e.value;
        e.value = null;
        count--;
        Entry head = e.next;
        for (Entry p = first; p != e; p = p.next) 
          head = new Entry(p.hash, p.key, p.value, head);
        
        tab[index] = head;
        recordModification(head);
        return oldValue;
      }
    }
    return null;
  }

  /**
   * Returns <tt>true</tt> if this map maps one or more keys to the
   * specified value. Note: This method requires a full internal
   * traversal of the hash table, and so is much slower than
   * method <tt>containsKey</tt>.
   *
   * @param value value whose presence in this map is to be tested.
   * @return <tt>true</tt> if this map maps one or more keys to the
   * specified value.  
   * @exception  NullPointerException  if the value is <code>null</code>.
   */
  public boolean containsValue(Object value) {
    if (value == null) throw new NullPointerException();
    Entry tab[] = getTableForReading();
    
    for (int i = 0 ; i < tab.length; ++i) {
      for (Entry e = tab[i] ; e != null ; e = e.next) 
        if (value.equals(e.value))
          return true;
    }
    return false;
  }
  /**
   * Tests if some key maps into the specified value in this table.
   * This operation is more expensive than the <code>containsKey</code>
   * method.<p>
   *
   * Note that this method is identical in functionality to containsValue,
   * (which is part of the Map interface in the collections framework).
   * 
   * @param      value   a value to search for.
   * @return     <code>true</code> if and only if some key maps to the
   *             <code>value</code> argument in this table as 
   *             determined by the <tt>equals</tt> method;
   *             <code>false</code> otherwise.
   * @exception  NullPointerException  if the value is <code>null</code>.
   * @see        #containsKey(Object)
   * @see        #containsValue(Object)
   * @see    Map
   */
  public boolean contains(Object value) {
    return containsValue(value);
  }

  /**
   * Copies all of the mappings from the specified map to this one.
   * 
   * These mappings replace any mappings that this map had for any of the
   * keys currently in the specified Map.
   *
   * @param t Mappings to be stored in this map.
   */
  public synchronized void putAll(Map t) {
    int n = t.size();
    if (n == 0)
      return;
    // Expand enough to hold at least n elements without resizing.
    // We can only resize table by factor of two at a time.
    // It is faster to rehash with fewer elements, so do it now.
    while (n >= threshold)
      rehash();
    for (Iterator it = t.entrySet().iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entry) it.next();
      Object key = entry.getKey();
      Object value = entry.getValue();
      put(key, value);
    }
  }

  /**
   * Removes all mappings from this map.
   */
  public synchronized void clear() {
    Entry tab[] = table;
    for (int i = 0; i < tab.length ; ++i) { 
      // must invalidate all to force concurrent get"s to wait and then retry
      for (Entry e = tab[i]; e != null; e = e.next) 
        e.value = null; 
      tab[i] = null;
    }
    count = 0;
    recordModification(tab);
  }
  /**
   * Returns a shallow copy of this 
   * <tt>ConcurrentReaderHashMap</tt> instance: the keys and
   * values themselves are not cloned.
   *
   * @return a shallow copy of this map.
   */
  public synchronized Object clone() {
    try { 
      ConcurrentReaderHashMap t = (ConcurrentReaderHashMap)super.clone();
      t.keySet = null;
      t.entrySet = null;
      t.values = null;
      Entry[] tab = table;
      t.table = new Entry[tab.length];
      Entry[] ttab = t.table;
      for (int i = 0; i < tab.length; ++i) {
        Entry first = null;
        for (Entry e = tab[i]; e != null; e = e.next) 
          first = new Entry(e.hash, e.key, e.value, first);
        ttab[i] = first;
      }
      return t;
    } 
    catch (CloneNotSupportedException e) { 
      // this shouldn"t happen, since we are Cloneable
      throw new InternalError();
    }
  }
  // Views
  protected transient Set keySet = null;
  protected transient Set entrySet = null;
  protected transient Collection values = null;
  /**
   * Returns a set view of the keys contained in this map.  The set is
   * backed by the map, so changes to the map are reflected in the set, and
   * vice-versa.  The set supports element removal, which removes the
   * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
   * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
   * <tt>clear</tt> operations.  It does not support the <tt>add</tt> or
   * <tt>addAll</tt> operations.
   *
   * @return a set view of the keys contained in this map.
   */
  
  public Set keySet() {
    Set ks = keySet;
    return (ks != null)? ks : (keySet = new KeySet());
  }
  
  private class KeySet extends AbstractSet {
    public Iterator iterator() {
      return new KeyIterator();
    }
    public int size() {
      return ConcurrentReaderHashMap.this.size();
    }
    public boolean contains(Object o) {
      return ConcurrentReaderHashMap.this.containsKey(o);
    }
    public boolean remove(Object o) {
      return ConcurrentReaderHashMap.this.remove(o) != null;
    }
    public void clear() {
      ConcurrentReaderHashMap.this.clear();
    }
  }
  /**
   * Returns a collection view of the values contained in this map.  The
   * collection is backed by the map, so changes to the map are reflected in
   * the collection, and vice-versa.  The collection supports element
   * removal, which removes the corresponding mapping from this map, via the
   * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
   * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
   * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
   *
   * @return a collection view of the values contained in this map.
   */
  
  public Collection values() {
    Collection vs = values;
    return (vs != null)? vs : (values = new Values());
  }
  
  private class Values extends AbstractCollection {
    public Iterator iterator() {
      return new ValueIterator();
    }
    public int size() {
      return ConcurrentReaderHashMap.this.size();
    }
    public boolean contains(Object o) {
      return ConcurrentReaderHashMap.this.containsValue(o);
    }
    public void clear() {
      ConcurrentReaderHashMap.this.clear();
    }
  }
  /**
   * Returns a collection view of the mappings contained in this map.  Each
   * element in the returned collection is a <tt>Map.Entry</tt>.  The
   * collection is backed by the map, so changes to the map are reflected in
   * the collection, and vice-versa.  The collection supports element
   * removal, which removes the corresponding mapping from the map, via the
   * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
   * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
   * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
   *
   * @return a collection view of the mappings contained in this map.
   */
  
  public Set entrySet() {
    Set es = entrySet;
    return (es != null) ? es : (entrySet = new EntrySet());
  }
  private class EntrySet extends AbstractSet {
    public Iterator iterator() {
      return new HashIterator();
    }
    public boolean contains(Object o) {
      if (!(o instanceof Map.Entry))
        return false;
      Map.Entry entry = (Map.Entry)o;
      Object v = ConcurrentReaderHashMap.this.get(entry.getKey());
      return v != null && v.equals(entry.getValue());
    }
    public boolean remove(Object o) {
      if (!(o instanceof Map.Entry))
        return false;
      return ConcurrentReaderHashMap.this.findAndRemoveEntry((Map.Entry)o);
    }
    public int size() {
      return ConcurrentReaderHashMap.this.size();
    }
    public void clear() {
      ConcurrentReaderHashMap.this.clear();
    }
  }
  /**
   * Helper method for entrySet.remove
   **/
  protected synchronized boolean findAndRemoveEntry(Map.Entry entry) {
    Object key = entry.getKey();
    Object v = get(key);
    if (v != null && v.equals(entry.getValue())) {
      remove(key);
      return true;
    }
    else
      return false;
  }
  /**
   * Returns an enumeration of the keys in this table.
   *
   * @return  an enumeration of the keys in this table.
   * @see     Enumeration
   * @see     #elements()
   * @see #keySet()
   * @see Map
   */
  public Enumeration keys() {
    return new KeyIterator();
  }
  /**
   * Returns an enumeration of the values in this table.
   * Use the Enumeration methods on the returned object to fetch the elements
   * sequentially.
   *
   * @return  an enumeration of the values in this table.
   * @see     java.util.Enumeration
   * @see     #keys()
   * @see #values()
   * @see Map
   */
  
  public Enumeration elements() {
    return new ValueIterator();
  }

  /**
   * ConcurrentReaderHashMap collision list entry.
   */
  protected static class Entry implements Map.Entry {
    /* 
       The use of volatile for value field ensures that
       we can detect status changes without synchronization.
       The other fields are never changed, and are
       marked as final. 
    */
    protected final int hash;
    protected final Object key;
    protected final Entry next;
    protected volatile Object value;
    Entry(int hash, Object key, Object value, Entry next) {
      this.hash = hash;
      this.key = key;
      this.next = next;
      this.value = value;
    }
    // Map.Entry Ops 
    public Object getKey() {
      return key;
    }
    /**
     * Get the value.  Note: In an entrySet or entrySet.iterator,
     * unless the set or iterator is used under synchronization of the
     * table as a whole (or you can otherwise guarantee lack of
     * concurrent modification), <tt>getValue</tt> <em>might</em>
     * return null, reflecting the fact that the entry has been
     * concurrently removed. However, there are no assurances that
     * concurrent removals will be reflected using this method.
     * 
     * @return     the current value, or null if the entry has been 
     * detectably removed.
     **/
    public Object getValue() {
      return value; 
    }
    /**
     * Set the value of this entry.  Note: In an entrySet or
     * entrySet.iterator), unless the set or iterator is used under
     * synchronization of the table as a whole (or you can otherwise
     * guarantee lack of concurrent modification), <tt>setValue</tt>
     * is not strictly guaranteed to actually replace the value field
     * obtained via the <tt>get</tt> operation of the underlying hash
     * table in multithreaded applications.  If iterator-wide
     * synchronization is not used, and any other concurrent
     * <tt>put</tt> or <tt>remove</tt> operations occur, sometimes
     * even to <em>other</em> entries, then this change is not
     * guaranteed to be reflected in the hash table. (It might, or it
     * might not. There are no assurances either way.)
     *
     * @param      value   the new value.
     * @return     the previous value, or null if entry has been detectably
     * removed.
     * @exception  NullPointerException  if the value is <code>null</code>.
     * 
     **/
    public Object setValue(Object value) {
      if (value == null)
        throw new NullPointerException();
      Object oldValue = this.value;
      this.value = value;
      return oldValue;
    }
    public boolean equals(Object o) {
      if (!(o instanceof Map.Entry))
        return false;
      Map.Entry e = (Map.Entry)o;
      return (key.equals(e.getKey()) && value.equals(e.getValue()));
    }
    
    public int hashCode() {
      return  key.hashCode() ^ value.hashCode();
    }
    
    public String toString() {
      return key + "=" + value;
    }
  }
  protected class HashIterator implements Iterator, Enumeration {
    protected final Entry[] tab;           // snapshot of table
    protected int index;                   // current slot 
    protected Entry entry = null;          // current node of slot
    protected Object currentKey;           // key for current node
    protected Object currentValue;         // value for current node
    protected Entry lastReturned = null;   // last node returned by next
    protected HashIterator() {
      tab = ConcurrentReaderHashMap.this.getTableForReading();
      index = tab.length - 1;
    }
    public boolean hasMoreElements() { return hasNext(); }
    public Object nextElement() { return next(); }

    public boolean hasNext() {
      /*
        currentkey and currentValue are set here to ensure that next()
        returns normally if hasNext() returns true. This avoids
        surprises especially when final element is removed during
        traversal -- instead, we just ignore the removal during
        current traversal.  
      */
      for (;;) {
        if (entry != null) {
          Object v = entry.value;
          if (v != null) {
            currentKey = entry.key;
            currentValue = v;
            return true;
          }
          else
            entry = entry.next;
        }
        while (entry == null && index >= 0)
          entry = tab[index--];
        if (entry == null) {
          currentKey = currentValue = null;
          return false;
        }
      }
    }
    protected Object returnValueOfNext() { return entry; }
    public Object next() {
      if (currentKey == null && !hasNext())
        throw new NoSuchElementException();
      Object result = returnValueOfNext();
      lastReturned = entry;
      currentKey = currentValue = null;
      entry = entry.next;
      return result;
    }
    public void remove() {
      if (lastReturned == null)
        throw new IllegalStateException();
      ConcurrentReaderHashMap.this.remove(lastReturned.key);
      lastReturned = null;
    }
  }

  protected class KeyIterator extends HashIterator {
    protected Object returnValueOfNext() { return currentKey; }
  }
  
  protected class ValueIterator extends HashIterator {
    protected Object returnValueOfNext() { return currentValue; }
  }
  

  /**
   * Save the state of the <tt>ConcurrentReaderHashMap</tt> 
   * instance to a stream (i.e.,
   * serialize it).
   *
   * @serialData The <i>capacity</i> of the 
   * ConcurrentReaderHashMap (the length of the
   * bucket array) is emitted (int), followed  by the
   * <i>size</i> of the ConcurrentReaderHashMap (the number of key-value
   * mappings), followed by the key (Object) and value (Object)
   * for each key-value mapping represented by the ConcurrentReaderHashMap
   * The key-value mappings are emitted in no particular order.
   */
  private synchronized void writeObject(java.io.ObjectOutputStream s)
    throws IOException  {
    // Write out the threshold, loadfactor, and any hidden stuff
    s.defaultWriteObject();
    
    // Write out number of buckets
    s.writeInt(table.length);
    
    // Write out size (number of Mappings)
    s.writeInt(count);
    
    // Write out keys and values (alternating)
    for (int index = table.length-1; index >= 0; index--) {
      Entry entry = table[index];
      
      while (entry != null) {
        s.writeObject(entry.key);
        s.writeObject(entry.value);
        entry = entry.next;
      }
    }
  }
  /**
   * Reconstitute the <tt>ConcurrentReaderHashMap</tt> 
   * instance from a stream (i.e.,
   * deserialize it).
   */
  private synchronized void readObject(java.io.ObjectInputStream s)
    throws IOException, ClassNotFoundException  {
    // Read in the threshold, loadfactor, and any hidden stuff
    s.defaultReadObject();
    // Read in number of buckets and allocate the bucket array;
    int numBuckets = s.readInt();
    table = new Entry[numBuckets];
    
    // Read in size (number of Mappings)
    int size = s.readInt();
    
    // Read the keys and values, and put the mappings in the table
    for (int i=0; i<size; i++) {
      Object key = s.readObject();
      Object value = s.readObject();
      put(key, value);
    }
  }
  
  /** 
   * Return the number of slots in this table 
   **/
  public synchronized int capacity() {
    return table.length;
  }
  /** 
   * Return the load factor 
   **/
  public float loadFactor() {
    return loadFactor;
  }
}





Hash table with double hashing

     
import java.io.IOException;
public class HashTableWithDoubleHashing {
  private DataItem[] hashArray; 
  private int arraySize;
  private DataItem bufItem; // for deleted items
  HashTableWithDoubleHashing(int size) {
    arraySize = size;
    hashArray = new DataItem[arraySize];
    bufItem = new DataItem(-1);
  }
  public void displayTable() {
    System.out.print("Table: ");
    for (int j = 0; j < arraySize; j++) {
      if (hashArray[j] != null)
        System.out.print(hashArray[j].getKey() + " ");
      else
        System.out.print("** ");
    }
    System.out.println("");
  }
  public int hashFunc1(int key) {
    return key % arraySize;
  }
  public int hashFunc2(int key) {
    return 6 - key % 6;
  }
  public void insert(int key, DataItem item) {
    int hashVal = hashFunc1(key); // hash the key
    int stepSize = hashFunc2(key); // get step size
    // until empty cell or -1
    while (hashArray[hashVal] != null && hashArray[hashVal].getKey() != -1) {
      hashVal += stepSize; // add the step
      hashVal %= arraySize; // for wraparound
    }
    hashArray[hashVal] = item; // insert item
  }
  public DataItem delete(int key) {
    int hashVal = hashFunc1(key); 
    int stepSize = hashFunc2(key); // get step size
    while (hashArray[hashVal] != null) {
      if (hashArray[hashVal].getKey() == key) {
        DataItem temp = hashArray[hashVal]; // save item
        hashArray[hashVal] = bufItem; // delete item
        return temp; // return item
      }
      hashVal += stepSize; // add the step
      hashVal %= arraySize; // for wraparound
    }
    return null; // can"t find item
  }
  public DataItem find(int key) {
    int hashVal = hashFunc1(key); // hash the key
    int stepSize = hashFunc2(key); // get step size
    while (hashArray[hashVal] != null) {
      if (hashArray[hashVal].getKey() == key)
        return hashArray[hashVal]; // yes, return item
      hashVal += stepSize; // add the step
      hashVal %= arraySize; // for wraparound
    }
    return null; // can"t find item
  }
  public static void main(String[] args) throws IOException {
    int aKey;
    DataItem aDataItem;
    int size, initSize;
    size = 100;
    initSize = 10;
    HashTableWithDoubleHashing theHashTable = new HashTableWithDoubleHashing(
        size);
    for (int i = 0; i < initSize; i++) {
      aKey = (int) (java.lang.Math.random() * 2 * size);
      aDataItem = new DataItem(aKey);
      theHashTable.insert(aKey, aDataItem);
    }
    theHashTable.displayTable();
    aKey = 100;
    aDataItem = new DataItem(aKey);
    theHashTable.insert(aKey, aDataItem);
    aKey = 100;
    theHashTable.delete(aKey);
    aKey = 100;
    aDataItem = theHashTable.find(aKey);
    if (aDataItem != null)
      System.out.println("Found " + aKey);
    else
      System.out.println("Could not find " + aKey);
  }
}
class DataItem {
  private int data;
  public DataItem(int i) {
    data = i;
  }
  public int getKey() {
    return data;
  }
}





Hash table with linear probing

     
import java.io.IOException;
public class HashTable {
  private DataItem[] hashArray; 
  private int arraySize;
  private DataItem bufItem; // for deleted items
  public HashTable(int size) {
    arraySize = size;
    hashArray = new DataItem[arraySize];
    bufItem = new DataItem(-1); // deleted item key is -1
  }
  public void displayTable() {
    System.out.print("Table: ");
    for (int j = 0; j < arraySize; j++) {
      if (hashArray[j] != null)
        System.out.print(hashArray[j].getKey() + " ");
      else
        System.out.print("#");
    }
    System.out.println("");
  }
  public int hashFunction(int key) {
    return key % arraySize; 
  }
  public void insert(DataItem item){
    int key = item.getKey(); 
    int hashVal = hashFunction(key); // hash the key
    // until empty cell or -1,
    while (hashArray[hashVal] != null && hashArray[hashVal].getKey() != -1) {
      ++hashVal; // go to next cell
      hashVal %= arraySize; // wraparound if necessary
    }
    hashArray[hashVal] = item; // insert item
  }
  public DataItem delete(int key) {
    int hashVal = hashFunction(key); 
    while (hashArray[hashVal] != null) // until empty cell,
    { 
      if (hashArray[hashVal].getKey() == key) {
        DataItem temp = hashArray[hashVal]; // save item
        hashArray[hashVal] = bufItem; // delete item
        return temp;
      }
      ++hashVal; // go to next cell
      hashVal %= arraySize; // wraparound if necessary
    }
    return null; // can"t find item
  }
  public DataItem find(int key) // find item with key
  {
    int hashVal = hashFunction(key); // hash the key
    while (hashArray[hashVal] != null) // until empty cell,
    { 
      if (hashArray[hashVal].getKey() == key)
        return hashArray[hashVal]; // found, return item
      ++hashVal; // go to next cell
      hashVal %= arraySize; // wraparound if necessary
    }
    return null; // can"t find item
  }
  public static void main(String[] args) throws IOException {
    DataItem aDataItem;
    int aKey, size, initSize, keysPerCell;
    size = 150;
    initSize = 100;
    keysPerCell = 10;
    HashTable theHashTable = new HashTable(size);
    for (int j = 0; j < initSize; j++){
      aKey = (int) (java.lang.Math.random() * keysPerCell * size);
      aDataItem = new DataItem(aKey);
      theHashTable.insert(aDataItem);
    }
    theHashTable.displayTable();
    aDataItem = new DataItem(100);
    theHashTable.insert(aDataItem);
    theHashTable.delete(100);
    aDataItem = theHashTable.find(100);
    if (aDataItem != null) {
      System.out.println("Found " + 100);
    } else
      System.out.println("Could not find " + 100);
  }
}
class DataItem { 
  private int data; 
  public DataItem(int d) {
    data = d;
  }
  public int getKey() {
    return data;
  }
}





Hash table with separate chaining

     
import java.io.IOException;
class Link {
  private int data;
  public Link next;
  public Link(int d) {
    data = d;
  }
  public int getKey() {
    return data;
  }
  public void displayLink() {
    System.out.print(data + " ");
  }
}
class SortedList {
  private Link first;
  public SortedList() {
    first = null;
  }
  public void insert(Link theLink){
    int key = theLink.getKey();
    Link previous = null; // start at first
    Link current = first;
    // until end of list,
        //or current bigger than key,
    while (current != null && key > current.getKey()) { 
      previous = current;
      current = current.next; // go to next item
    }
    if (previous == null) // if beginning of list,
      first = theLink; 
    else
      // not at beginning,
      previous.next = theLink; 
    theLink.next = current; 
  }
  public void delete(int key){ 
    Link previous = null; 
    Link current = first;
    while (current != null && key != current.getKey()) { 
      previous = current;
      current = current.next; 
    }
    // disconnect link
    if (previous == null) //   if beginning of list delete first link
      first = first.next;       
    else
      //   not at beginning
      previous.next = current.next; //delete current link
  }
  public Link find(int key) {
    Link current = first; 
    while (current != null && current.getKey() <= key) { // or key too small,
      if (current.getKey() == key) // found, return link
        return current;  
      current = current.next; // go to next item
    }
    return null; // cannot find it
  }
  public void displayList() {
    System.out.print("List: ");
    Link current = first;
    while (current != null){
      current.displayLink(); 
      current = current.next;
    }
    System.out.println("");
  }
}
public class HashChain {
  private SortedList[] hashArray; 
  private int arraySize;
  public HashChain(int size) {
    arraySize = size;
    hashArray = new SortedList[arraySize];
    for (int i = 0; i < arraySize; i++)
      hashArray[i] = new SortedList(); 
  }
  public void displayTable() {
    for (int j = 0; j < arraySize; j++) {
      System.out.print(j + ". "); 
      hashArray[j].displayList(); 
    }
  }
  public int hashFunc(int key) {
    return key % arraySize;
  }
  public void insert(Link theLink) {
    int key = theLink.getKey();
    int hashVal = hashFunc(key); 
    hashArray[hashVal].insert(theLink); 
  }
  public void delete(int key) {
    int hashVal = hashFunc(key); // hash the key
    hashArray[hashVal].delete(key); 
  }
  public Link find(int key) {
    int hashVal = hashFunc(key); // hash the key
    Link theLink = hashArray[hashVal].find(key); // get link
    return theLink;
  }
  public static void main(String[] args) throws IOException {
    int aKey;
    Link dataItem;
    int size, initSize, keysPerCell = 100;
    size = 100;
    initSize = 10;
    HashChain hashTable = new HashChain(size);
    for (int i = 0; i < initSize; i++){
      aKey = (int) (java.lang.Math.random() * keysPerCell * size);
      dataItem = new Link(aKey);
      hashTable.insert(dataItem);
    }
    hashTable.displayTable();
    aKey = 100;
    dataItem = new Link(aKey);
    hashTable.insert(dataItem);
    aKey = 100;
    hashTable.delete(aKey);
    aKey = 50;
    dataItem = hashTable.find(aKey);
    if (dataItem != null)
      System.out.println("Found " + aKey);
    else
      System.out.println("Could not find " + aKey);
  }
}





Iterate through keys of Java Hashtable

     
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    Enumeration e = ht.keys();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());
    }
  }
}





Iterate through values of Java Hashtable

     

import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    Enumeration e = ht.elements();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());
    }
  }
}





Lru Hashtable

   
// LruHashtable - a Hashtable that expires least-recently-used objects
//
// Copyright (C) 1996 by Jef Poskanzer <jef@acme.ru>.  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// Visit the ACME Labs Java page for up-to-date versions of this and other
// fine Java utilities: http://www.acme.ru/java/
//
// moved to the net.matuschek.util package by Daniel Matuschek
//

import java.util.Enumeration;
import java.util.Hashtable;
/** 
 * A Hashtable that expires least-recently-used objects.
 * 
 * <p>Use just like java.util.Hashtable, except that the initial-capacity
 * parameter is required.  Instead of growing bigger than that size,
 * it will throw out objects that haven"t been looked at in a while.
 * </p>
 *
 * @author Jef Poskanzer
 * @author Daniel Matuschek
 * @version $Id: LruHashtable.java,v 1.3 2002/05/31 14:45:56 matuschd Exp $
 *
 * @see java.util.Hashtable
 */
public class LruHashtable extends Hashtable
{
  
  // Number of buckets.
  private static final int nBuckets = 2;
  
  // Load factor.
  private float loadFactor;
  
  // When count exceeds this threshold, expires the old table.
  private int threshold;
  
  // Capacity of each bucket.
  private int eachCapacity;
  
  // The tables.
  private Hashtable oldTable;
  private Hashtable newTable;
  
  /// Constructs a new, empty hashtable with the specified initial 
  // capacity and the specified load factor.
  // Unlike a plain Hashtable, an LruHashtable will never grow or
  // shrink from this initial capacity.
  // @param initialCapacity the initial number of buckets
  // @param loadFactor a number between 0.0 and 1.0, it defines
  //    the threshold for expiring old entries
  // @exception IllegalArgumentException If the initial capacity
  // is less than or equal to zero.
  // @exception IllegalArgumentException If the load factor is
  // less than or equal to zero.
  public LruHashtable( int initialCapacity, float loadFactor )
  {
    // We have to call a superclass constructor, but we"re not actually
    // going to use it at all.  The only reason we want to extend Hashtable
    // is for type conformance.  So, make a parent hash table of minimum
    // size and then ignore it.
    super( 1 );
    
    if ( initialCapacity <= 0 || loadFactor <= 0.0 )
      throw new IllegalArgumentException();
    this.loadFactor = loadFactor;
    threshold = (int) ( initialCapacity * loadFactor ) - 1;
    eachCapacity = initialCapacity / nBuckets + 1;
    oldTable = new Hashtable( eachCapacity, loadFactor );
    newTable = new Hashtable( eachCapacity, loadFactor );
  }
  
  /// Constructs a new, empty hashtable with the specified initial 
  // capacity.
  // Unlike a plain Hashtable, an LruHashtable will never grow or
  // shrink from this initial capacity.
  // @param initialCapacity the initial number of buckets
  public LruHashtable( int initialCapacity )
  {
    this( initialCapacity, 0.75F );
  }
  
  /// Returns the number of elements contained in the hashtable. 
  public int size()
  {
    return newTable.size() + oldTable.size();
  }
  
  /// Returns true if the hashtable contains no elements.
  public boolean isEmpty()
  {
    return size() == 0;
  }
  
  /// Returns an enumeration of the hashtable"s keys.
  // @see LruHashtable#elements
  // @see Enumeration
  public synchronized Enumeration keys()
  {
    return new LruHashtableEnumerator( oldTable, newTable, true );
  }
  
  /// Returns an enumeration of the elements. Use the Enumeration methods 
  // on the returned object to fetch the elements sequentially.
  // @see LruHashtable#keys
  // @see Enumeration
  public synchronized Enumeration elements()
  {
    return new LruHashtableEnumerator( oldTable, newTable, false );
  }
  
  /// Returns true if the specified object is an element of the hashtable.
  // This operation is more expensive than the containsKey() method.
  // @param value the value that we are looking for
  // @exception NullPointerException If the value being searched 
  // for is equal to null.
  // @see LruHashtable#containsKey
  public synchronized boolean contains( Object value )
  {
    if ( newTable.contains( value ) )
      return true;
    if ( oldTable.contains( value ) )
      {
  // We would like to move the object from the old table to the
  // new table.  However, we need keys to re-add the objects, and
  // there"s no good way to find all the keys for the given object.
  // We"d have to enumerate through all the keys and check each
  // one.  Yuck.  For now we just punt.  Anyway, contains() is
  // probably not a commonly-used operation.
  return true;
      }
    return false;
  }
  
  /// Returns true if the collection contains an element for the key.
  // @param key the key that we are looking for
  // @see LruHashtable#contains
  public synchronized boolean containsKey( Object key )
  {
    if ( newTable.containsKey( key ) )
      return true;
    if ( oldTable.containsKey( key ) )
      {
  // Move object from old table to new table.
  Object value = oldTable.get( key );
  newTable.put( key, value );
  oldTable.remove( key );
  return true;
      }
    return false;
  }
  
  /// Gets the object associated with the specified key in the 
  // hashtable.
  // @param key the specified key
  // @returns the element for the key or null if the key
  //    is not defined in the hash table.
  // @see LruHashtable#put
  public synchronized Object get( Object key )
  {
    Object value;
    value = newTable.get( key );
    if ( value != null )
      return value;
    value = oldTable.get( key );
    if ( value != null )
      {
  // Move object from old table to new table.
  newTable.put( key, value );
  oldTable.remove( key );
  return value;
      }
    return null;
  }
  
  /// Puts the specified element into the hashtable, using the specified
  // key.  The element may be retrieved by doing a get() with the same key.
  // The key and the element cannot be null. 
  // @param key the specified key in the hashtable
  // @param value the specified element
  // @exception NullPointerException If the value of the element 
  // is equal to null.
  // @see LruHashtable#get
  // @return the old value of the key, or null if it did not have one.
  public synchronized Object put( Object key, Object value )
  {
    Object oldValue = newTable.put( key, value );
    if ( oldValue != null )
      return oldValue;
    oldValue = oldTable.get( key );
    if ( oldValue != null )
      oldTable.remove( key );
    else
      {
  if ( size() >= threshold )
    {
      // Rotate the tables.
      oldTable = newTable;
      newTable = new Hashtable( eachCapacity, loadFactor );
    } 
      }
    return oldValue;
  }
  
  /// Removes the element corresponding to the key. Does nothing if the
  // key is not present.
  // @param key the key that needs to be removed
  // @return the value of key, or null if the key was not found.
  public synchronized Object remove( Object key )
  {
    Object oldValue = newTable.remove( key );
    if ( oldValue == null )
      oldValue = oldTable.remove( key );
    return oldValue;
  }
  
  /// Clears the hash table so that it has no more elements in it.
  public synchronized void clear()
  {
    newTable.clear();
    oldTable.clear();
  }
  
  /// Creates a clone of the hashtable. A shallow copy is made,
  // the keys and elements themselves are NOT cloned. This is a
  // relatively expensive operation.
  public synchronized Object clone()
  {
    LruHashtable n = (LruHashtable) super.clone();
    n.newTable = (Hashtable) n.newTable.clone();
    n.oldTable = (Hashtable) n.oldTable.clone();
    return n;
  }
  
  // toString() can be inherited.
  
}

class LruHashtableEnumerator implements Enumeration
{
  Enumeration oldEnum;
  Enumeration newEnum;
  boolean old;
  
  LruHashtableEnumerator( Hashtable oldTable, Hashtable newTable, boolean keys )
  {
    if ( keys )
      {
  oldEnum = oldTable.keys();
  newEnum = newTable.keys();
      }
    else
      {
  oldEnum = oldTable.elements();
  newEnum = newTable.elements();
      }
    old = true;
  }
  
  public boolean hasMoreElements()
  {
    boolean r;
    if ( old )
      {
  r = oldEnum.hasMoreElements();
  if ( ! r )
    {
      old = false;
      r = newEnum.hasMoreElements();
    }
      }
    else
      r = newEnum.hasMoreElements();
    return r;
  }
  
  public Object nextElement()
  {
    if ( old )
      return oldEnum.nextElement();
    return newEnum.nextElement();
  }
  
}





MultiMap extends AbstractMap

     
import java.util.*;
public class MultiMap extends AbstractMap {
    
  private Map map;
  public MultiMap() {
    this(null);
  }
  public MultiMap(Map copy) {
    map = new HashMap();
    if (copy != null) {
      Iterator iter = copy.entrySet().iterator();
      while(iter.hasNext()) {
        Map.Entry entry = (Map.Entry)iter.next();
        add(entry.getKey(), entry.getValue());
      }
    }
  }
  public boolean containsKey(Object key) {
    Collection values = (Collection)map.get(key);
    return ((values != null) && (values.size() != 0));
  }
    
  public boolean containsValue(Object value) {
    Iterator iter = map.entrySet().iterator();
    boolean found = false;
    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry)iter.next();
      Collection values = (Collection)entry.getValue();
      if (values.contains(value)) {
        found = true;
        break;
      }
    }
    return found;
  }

  public Object get(Object key) {
    return map.get(key);
  }
  public Object put(Object key, Object value) {
    if (!(value instanceof Collection)) {
      throw new IllegalArgumentException(value.getClass().toString());
    }
    Object original = get(key);
    map.put(key, value);
    return original;
  }
  public boolean add(Object key, Object value) {
    return getValues(key).add(value);
  }
    
  public boolean addAll(Object key, Collection values) {
    return getValues(key).addAll(values);
  }
  private Collection getValues(Object key) {
    Collection col = (Collection)map.get(key);
    if (col == null) {
      col = new HashSet();
      map.put(key, col);
    }
    return col;
  }
  public Object remove(Object key) {
    Object original = get(key);
    map.remove(key);
    return original;
  }
  public boolean remove(Object key, Object value) {
    Collection values = (Collection)map.get(key);
    if (values == null) {
      return false;
    } else {
      return values.remove(value);
    }
  }
  public void clear() {
    map.clear();
  }
  public String toString() {
    StringBuffer buff = new StringBuffer();
    buff.append("{");
    Iterator keys = map.keySet().iterator();
    boolean first = true;
    while (keys.hasNext()) {
      if (first) {
        first = false;
      } else {
        buff.append(", ");
      }
      Object key = keys.next();
      Collection values = getValues(key);
      buff.append("[" + key + ": " + values + "]");
    }
    buff.append("}");
    return buff.toString();
  }
  public Set entrySet() {
    int size = 0;
    Iterator iterKeys = map.entrySet().iterator();
    while (iterKeys.hasNext()) {
      Map.Entry entry = (Map.Entry)iterKeys.next();
      Collection values = (Collection)entry.getValue();
      Iterator iterValues = values.iterator();
      while (iterValues.hasNext()) { 
        size++;
        iterValues.next();
      }
    }
    final int finalSize = size;
    final Iterator entries = map.entrySet().iterator();
    return new AbstractSet() {
      int pos = 0;
      Map.Entry entry;
      Iterator values;
      public Iterator iterator() { 
        return new Iterator() {
          public void remove() {
            throw new UnsupportedOperationException();
          }
          public boolean hasNext() {
            return pos != finalSize;
          }
          public Object next() {
            while(true) {
              if (entry == null) {
                entry = (Map.Entry)entries.next();
                values = ((Collection)entry.getValue()).iterator();
              }
              Object key = entry.getKey();
              if (values.hasNext()) {
                Object value = values.next();
                pos++;
                return new Entry(key, value);
              } else {
                entry = null;
              }
            }
          }
        };
      }
      public int size() {
        return finalSize;
      }
    };
  }
  private static class Entry implements Map.Entry {
    Object key;
    Object value;
    Entry(Object key, Object value) {
      this.key = key;
      this.value = value;
    }
    public Object getKey() {
      return key;
    }
    public Object getValue() {
      return value;
    }
    public Object setValue(Object value) {
      Object oldValue = this.value;
      this.value = value;
      return oldValue;
    }
    public boolean equals(Object o) {
      if (!(o instanceof Map.Entry)) {
        return false;
      } else {
        Map.Entry e = (Map.Entry)o;
        return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
          (value==null ? e.getValue()==null : value.equals(e.getValue()));
      }
    }
    public int hashCode() {
      return ((value==null) ? 0 : value.hashCode());
    }
    public String toString() {
      return key+"="+value;
    }
  }
  public static void main (String args[]) {
    Map map = new HashMap();
    map.put("one", "two");
    map.put("three", "four");
    map.put("five", "six");
    MultiMap multi = new MultiMap(map);
    System.out.println(multi);
    multi.add("five", "seven");
    multi.add("five", "eight");
    multi.add("five", "nine");
    multi.add("five", "ten");
    multi.add("three", "seven");
    System.out.println(multi);
    multi.remove("three");
    System.out.println(multi);
  }
}





Remove all values from Java Hashtable

     

import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    ht.clear();
    System.out.println(ht.size());
  }
}





Remove value from Java Hashtable

     
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
  public static void main(String[] args) {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");
    Object obj = ht.remove("2");
    System.out.println(obj + " was Removed ");
    Enumeration e = ht.elements();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());
    }
  }
}





Scan the content of a hashtable

     
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
  public static void main(String args[]) {
    Hashtable<String,String> hash = new Hashtable<String,String>();
    hash.put("1","one");
    hash.put("2","two");
    hash.put("3","three");
    
    
    Enumeration keys = hash.keys();
    while (keys.hasMoreElements()) {
      Object key = keys.nextElement();
      Object value = hash.get(key);
      
      System.out.println(key+" : "+value);
    }
  }
}





Simple demonstration of HashMap

     
// : c11:Statistics.java
// Simple demonstration of HashMap.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
class Counter {
  int i = 1;
  public String toString() {
    return Integer.toString(i);
  }
}
public class Statistics {
  private static Random rand = new Random();
  public static void main(String[] args) {
    Map hm = new HashMap();
    for (int i = 0; i < 10000; i++) {
      // Produce a number between 0 and 20:
      Integer r = new Integer(rand.nextInt(20));
      if (hm.containsKey(r))
        ((Counter) hm.get(r)).i++;
      else
        hm.put(r, new Counter());
    }
    System.out.println(hm);
  }
} ///:~





Sorting Elements in a TreeMap

     
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class DiameterMap {
  public static void main(String args[]) {
    String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter",
        "Saturn", "Uranus", "Neptune", "Pluto" };
    float diameters[] = { 4800f, 12103.6f, 12756.3f, 6794f, 142984f,
        120536f, 51118f, 49532f, 2274f };
    Map map = new TreeMap();
    for (int i = 0, n = names.length; i < n; i++) {
      map.put(names[i], new Float(diameters[i]));
    }
    Iterator it = map.keySet().iterator();
    Object obj;
    while (it.hasNext()) {
      obj = it.next();
      System.out.println(obj + ": " + map.get(obj));
    }
  }
}





Sort keys in an Hashtable

     
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
public class Main {
  public static void main(String args[]) {
    Hashtable<String, String> h = new Hashtable<String, String>();
    h.put("a", "b");
    h.put("c", "d");
    h.put("e", "f");
    for (String str : h.keySet()) {
      System.out.println(str);
    }
    List<String> v = new ArrayList<String>(h.keySet());
    Collections.sort(v);
    for (String str : v) {
      System.out.println(str + " " + (String) h.get(str));
    }
  }
}





Use treemap

     
import java.util.Map;
import java.util.TreeMap;
public class Freq {
  private static final Integer ONE = new Integer(1);
  public static void main(String args[]) {
    Map m = new TreeMap();
    m.put("a Key", "a Value");
    m.put("jexp", "www.jexp.ru");
    System.out.println(m.size() + " keys detected:");
    System.out.println(m);
  }
}





What you can do with a TreeMap

     
// : c11:SortedMapDemo.java
//What you can do with a TreeMap.
//From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
//www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.Iterator;
import java.util.TreeMap;
public class SortedMapDemo {
  public static void main(String[] args) {
    TreeMap sortedMap = new TreeMap();
    sortedMap.put("Adobe", "Mountain View, CA");
    sortedMap.put("IBM", "White Plains, NY");
    sortedMap.put("Learning Tree", "Los Angeles, CA");
    sortedMap.put("Microsoft", "Redmond, WA");
    sortedMap.put("Netscape", "Mountain View, CA");
    sortedMap.put("O"Reilly", "Sebastopol, CA");
    sortedMap.put("Sun", "Mountain View, CA");
    System.out.println(sortedMap);
    Object low = sortedMap.firstKey(), high = sortedMap.lastKey();
    System.out.println(low);
    System.out.println(high);
    Iterator it = sortedMap.keySet().iterator();
    for (int i = 0; i <= 6; i++) {
      if (i == 3)
        low = it.next();
      if (i == 6)
        high = it.next();
      else
        it.next();
    }
    System.out.println(low);
    System.out.println(high);
    System.out.println(sortedMap.subMap(low, high));
    System.out.println(sortedMap.headMap(high));
    System.out.println(sortedMap.tailMap(low));
  }
} ///:~





Working with Key-Value Pairs in a Hashtable

     
import java.util.Enumeration;
import java.util.Hashtable;
public class PlanetDiameters {
  public static void main(String args[]) {
    String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter",
        "Saturn", "Uranus", "Neptune", "Pluto" };
    float diameters[] = { 4800f, 12103.6f, 12756.3f, 6794f, 142984f,
        120536f, 51118f, 49532f, 2274f };
    Hashtable hash = new Hashtable();
    for (int i = 0, n = names.length; i < n; i++) {
      hash.put(names[i], new Float(diameters[i]));
    }
    Enumeration e = hash.keys();
    Object obj;
    while (e.hasMoreElements()) {
      obj = e.nextElement();
      System.out.println(obj + ": " + hash.get(obj));
    }
  }
}