⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hashtable.java

📁 gcc的组建
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* Hashtable.java -- a class providing a basic hashtable data structure,   mapping Object --> Object   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006   Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version.GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING.  If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version. */package java.util;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;// NOTE: This implementation is very similar to that of HashMap. If you fix// a bug in here, chances are you should make a similar change to the HashMap// code./** * A class which implements a hashtable data structure. * <p> * * This implementation of Hashtable uses a hash-bucket approach. That is: * linear probing and rehashing is avoided; instead, each hashed value maps * to a simple linked-list which, in the best case, only has one node. * Assuming a large enough table, low enough load factor, and / or well * implemented hashCode() methods, Hashtable should provide O(1) * insertion, deletion, and searching of keys.  Hashtable is O(n) in * the worst case for all of these (if all keys hash to the same bucket). * <p> * * This is a JDK-1.2 compliant implementation of Hashtable.  As such, it * belongs, partially, to the Collections framework (in that it implements * Map).  For backwards compatibility, it inherits from the obsolete and * utterly useless Dictionary class. * <p> * * Being a hybrid of old and new, Hashtable has methods which provide redundant * capability, but with subtle and even crucial differences. * For example, one can iterate over various aspects of a Hashtable with * either an Iterator (which is the JDK-1.2 way of doing things) or with an * Enumeration.  The latter can end up in an undefined state if the Hashtable * changes while the Enumeration is open. * <p> * * Unlike HashMap, Hashtable does not accept `null' as a key value. Also, * all accesses are synchronized: in a single thread environment, this is * expensive, but in a multi-thread environment, this saves you the effort * of extra synchronization. However, the old-style enumerators are not * synchronized, because they can lead to unspecified behavior even if * they were synchronized. You have been warned. * <p> * * The iterators are <i>fail-fast</i>, meaning that any structural * modification, except for <code>remove()</code> called on the iterator * itself, cause the iterator to throw a * <code>ConcurrentModificationException</code> rather than exhibit * non-deterministic behavior. * * @author Jon Zeppieri * @author Warren Levy * @author Bryce McKinlay * @author Eric Blake (ebb9@email.byu.edu) * @see HashMap * @see TreeMap * @see IdentityHashMap * @see LinkedHashMap * @since 1.0 * @status updated to 1.4 */public class Hashtable extends Dictionary  implements Map, Cloneable, Serializable{  // WARNING: Hashtable is a CORE class in the bootstrap cycle. See the  // comments in vm/reference/java/lang/Runtime for implications of this fact.  /** Default number of buckets. This is the value the JDK 1.3 uses. Some   * early documentation specified this value as 101. That is incorrect.   */  private static final int DEFAULT_CAPACITY = 11;  /** An "enum" of iterator types. */  // Package visible for use by nested classes.  static final int KEYS = 0,                   VALUES = 1,                   ENTRIES = 2;  /**   * The default load factor; this is explicitly specified by the spec.   */  private static final float DEFAULT_LOAD_FACTOR = 0.75f;  /**   * Compatible with JDK 1.0+.   */  private static final long serialVersionUID = 1421746759512286392L;  /**   * The rounded product of the capacity and the load factor; when the number   * of elements exceeds the threshold, the Hashtable calls   * <code>rehash()</code>.   * @serial   */  private int threshold;  /**   * Load factor of this Hashtable:  used in computing the threshold.   * @serial   */  private final float loadFactor;  /**   * Array containing the actual key-value mappings.   */  // Package visible for use by nested classes.  transient HashEntry[] buckets;  /**   * Counts the number of modifications this Hashtable has undergone, used   * by Iterators to know when to throw ConcurrentModificationExceptions.   */  // Package visible for use by nested classes.  transient int modCount;  /**   * The size of this Hashtable:  denotes the number of key-value pairs.   */  // Package visible for use by nested classes.  transient int size;  /**   * The cache for {@link #keySet()}.   */  private transient Set keys;  /**   * The cache for {@link #values()}.   */  private transient Collection values;  /**   * The cache for {@link #entrySet()}.   */  private transient Set entries;  /**   * Class to represent an entry in the hash table. Holds a single key-value   * pair. A Hashtable Entry is identical to a HashMap Entry, except that   * `null' is not allowed for keys and values.   */  private static final class HashEntry extends AbstractMap.BasicMapEntry  {    /** The next entry in the linked list. */    HashEntry next;    /**     * Simple constructor.     * @param key the key, already guaranteed non-null     * @param value the value, already guaranteed non-null     */    HashEntry(Object key, Object value)    {      super(key, value);    }    /**     * Resets the value.     * @param newVal the new value     * @return the prior value     * @throws NullPointerException if <code>newVal</code> is null     */    public Object setValue(Object newVal)    {      if (newVal == null)        throw new NullPointerException();      return super.setValue(newVal);    }  }  /**   * Construct a new Hashtable with the default capacity (11) and the default   * load factor (0.75).   */  public Hashtable()  {    this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);  }  /**   * Construct a new Hashtable from the given Map, with initial capacity   * the greater of the size of <code>m</code> or the default of 11.   * <p>   *   * Every element in Map m will be put into this new Hashtable.   *   * @param m a Map whose key / value pairs will be put into   *          the new Hashtable.  <b>NOTE: key / value pairs   *          are not cloned in this constructor.</b>   * @throws NullPointerException if m is null, or if m contains a mapping   *         to or from `null'.   * @since 1.2   */  public Hashtable(Map m)  {    this(Math.max(m.size() * 2, DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);    putAll(m);  }  /**   * Construct a new Hashtable with a specific inital capacity and   * default load factor of 0.75.   *   * @param initialCapacity the initial capacity of this Hashtable (&gt;= 0)   * @throws IllegalArgumentException if (initialCapacity &lt; 0)   */  public Hashtable(int initialCapacity)  {    this(initialCapacity, DEFAULT_LOAD_FACTOR);  }  /**   * Construct a new Hashtable with a specific initial capacity and   * load factor.   *   * @param initialCapacity the initial capacity (&gt;= 0)   * @param loadFactor the load factor (&gt; 0, not NaN)   * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||   *                                     ! (loadFactor &gt; 0.0)   */  public Hashtable(int initialCapacity, float loadFactor)  {    if (initialCapacity < 0)      throw new IllegalArgumentException("Illegal Capacity: "                                         + initialCapacity);    if (! (loadFactor > 0)) // check for NaN too      throw new IllegalArgumentException("Illegal Load: " + loadFactor);    if (initialCapacity == 0)      initialCapacity = 1;    buckets = new HashEntry[initialCapacity];    this.loadFactor = loadFactor;    threshold = (int) (initialCapacity * loadFactor);  }  /**   * Returns the number of key-value mappings currently in this hashtable.   * @return the size   */  public synchronized int size()  {    return size;  }  /**   * Returns true if there are no key-value mappings currently in this table.   * @return <code>size() == 0</code>   */  public synchronized boolean isEmpty()  {    return size == 0;  }  /**   * Return an enumeration of the keys of this table. There's no point   * in synchronizing this, as you have already been warned that the   * enumeration is not specified to be thread-safe.   *   * @return the keys   * @see #elements()   * @see #keySet()   */  public Enumeration keys()  {    return new Enumerator(KEYS);  }  /**   * Return an enumeration of the values of this table. There's no point   * in synchronizing this, as you have already been warned that the   * enumeration is not specified to be thread-safe.   *   * @return the values   * @see #keys()   * @see #values()   */  public Enumeration elements()  {    return new Enumerator(VALUES);  }  /**   * Returns true if this Hashtable contains a value <code>o</code>,   * such that <code>o.equals(value)</code>.  This is the same as   * <code>containsValue()</code>, and is O(n).   * <p>   *   * @param value the value to search for in this Hashtable   * @return true if at least one key maps to the value   * @throws NullPointerException if <code>value</code> is null   * @see #containsValue(Object)   * @see #containsKey(Object)   */  public synchronized boolean contains(Object value)  {    if (value == null)      throw new NullPointerException();    for (int i = buckets.length - 1; i >= 0; i--)      {        HashEntry e = buckets[i];        while (e != null)          {            if (e.value.equals(value))              return true;            e = e.next;          }      }     return false;    }  /**   * Returns true if this Hashtable contains a value <code>o</code>, such that   * <code>o.equals(value)</code>. This is the new API for the old   * <code>contains()</code>.   *   * @param value the value to search for in this Hashtable   * @return true if at least one key maps to the value   * @see #contains(Object)   * @see #containsKey(Object)   * @throws NullPointerException if <code>value</code> is null   * @since 1.2   */  public boolean containsValue(Object value)  {    // Delegate to older method to make sure code overriding it continues     // to work.    return contains(value);  }  /**   * Returns true if the supplied object <code>equals()</code> a key   * in this Hashtable.   *   * @param key the key to search for in this Hashtable   * @return true if the key is in the table   * @throws NullPointerException if key is null   * @see #containsValue(Object)   */  public synchronized boolean containsKey(Object key)  {    int idx = hash(key);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -