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

📄 identityhashmap.java

📁 this gcc-g++-3.3.1.tar.gz is a source file of gcc, you can learn more about gcc through this codes f
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* IdentityHashMap.java -- a class providing a hashtable data structure,   mapping Object --> Object, which uses object identity for hashing.   Copyright (C) 2001, 2002 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., 59 Temple Place, Suite 330, Boston, MA02111-1307 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.*;/** * This class provides a hashtable-backed implementation of the * Map interface, but uses object identity to do its hashing.  In fact, * it uses object identity for comparing values, as well. It uses a * linear-probe hash table, which may have faster performance * than the chaining employed by HashMap. * <p> * * <em>WARNING: This is not a general purpose map. Because it uses * System.identityHashCode and ==, instead of hashCode and equals, for * comparison, it violated Map's general contract, and may cause * undefined behavior when compared to other maps which are not * IdentityHashMaps.  This is designed only for the rare cases when * identity semantics are needed.</em> An example use is * topology-preserving graph transformations, such as deep cloning, * or as proxy object mapping such as in debugging. * <p> * * This map permits <code>null</code> keys and values, and does not * guarantee that elements will stay in the same order over time. The * basic operations (<code>get</code> and <code>put</code>) take * constant time, provided System.identityHashCode is decent. You can * tune the behavior by specifying the expected maximum size. As more * elements are added, the map may need to allocate a larger table, * which can be expensive. * <p> * * This implementation is unsynchronized.  If you want multi-thread * access to be consistent, you must synchronize it, perhaps by using * <code>Collections.synchronizedMap(new IdentityHashMap(...));</code>. * The iterators are <i>fail-fast</i>, meaning that a structural modification * made to the map outside of an iterator's remove method cause the * iterator, and in the case of the entrySet, the Map.Entry, to * fail with a {@link ConcurrentModificationException}. * * @author Tom Tromey <tromey@redhat.com> * @author Eric Blake <ebb9@email.byu.edu> * @see System#identityHashCode(Object) * @see Collection * @see Map * @see HashMap * @see TreeMap * @see LinkedHashMap * @see WeakHashMap * @since 1.4 * @status updated to 1.4 */public class IdentityHashMap extends AbstractMap  implements Map, Serializable, Cloneable{  /** The default capacity. */  private static final int DEFAULT_CAPACITY = 21;  /**   * This object is used to mark deleted items. Package visible for use by   * nested classes.   */  static final Object tombstone = new Object();  /**   * This object is used to mark empty slots.  We need this because   * using null is ambiguous. Package visible for use by nested classes.   */  static final Object emptyslot = new Object();  /**   * Compatible with JDK 1.4.   */  private static final long serialVersionUID = 8188218128353913216L;  /**   * The number of mappings in the table. Package visible for use by nested   * classes.   * @serial   */  int size;  /**   * The table itself. Package visible for use by nested classes.   */  transient Object[] table;  /**   * The number of structural modifications made so far. Package visible for   * use by nested classes.   */  transient int modCount;  /**   * The cache for {@link #entrySet()}.   */  private transient Set entries;  /**   * The threshold for rehashing, which is 75% of (table.length / 2).   */  private transient int threshold;  /**   * Create a new IdentityHashMap with the default capacity (21 entries).   */  public IdentityHashMap()  {    this(DEFAULT_CAPACITY);  }  /**   * Create a new IdentityHashMap with the indicated number of   * entries.  If the number of elements added to this hash map   * exceeds this maximum, the map will grow itself; however, that   * incurs a performance penalty.   *   * @param max initial size   * @throws IllegalArgumentException if max is negative   */  public IdentityHashMap(int max)  {    if (max < 0)      throw new IllegalArgumentException();    // Need at least two slots, or hash() will break.    if (max < 2)      max = 2;    table = new Object[max << 1];    Arrays.fill(table, emptyslot);    threshold = (max >> 2) * 3;  }  /**   * Create a new IdentityHashMap whose contents are taken from the   * given Map.   *   * @param m The map whose elements are to be put in this map   * @throws NullPointerException if m is null   */  public IdentityHashMap(Map m)  {    this(Math.max(m.size() << 1, DEFAULT_CAPACITY));    putAll(m);  }  /**   * Remove all mappings from this map.   */  public void clear()  {    if (size != 0)      {        modCount++;        Arrays.fill(table, emptyslot);        size = 0;      }  }  /**   * Creates a shallow copy where keys and values are not cloned.   */  public Object clone()  {    try      {        IdentityHashMap copy = (IdentityHashMap) super.clone();        copy.table = (Object[]) table.clone();        copy.entries = null; // invalidate the cache        return copy;      }    catch (CloneNotSupportedException e)      {        // Can't happen.        return null;      }  }  /**   * Tests whether the specified key is in this map.  Unlike normal Maps,   * this test uses <code>entry == key</code> instead of   * <code>entry == null ? key == null : entry.equals(key)</code>.   *   * @param key the key to look for   * @return true if the key is contained in the map   * @see #containsValue(Object)   * @see #get(Object)   */  public boolean containsKey(Object key)  {    return key == table[hash(key)];  }  /**   * Returns true if this HashMap contains the value.  Unlike normal maps,   * this test uses <code>entry == value</code> instead of   * <code>entry == null ? value == null : entry.equals(value)</code>.   *   * @param value the value to search for in this HashMap   * @return true if at least one key maps to the value   * @see #containsKey(Object)   */  public boolean containsValue(Object value)  {    for (int i = table.length - 1; i > 0; i -= 2)      if (table[i] == value)        return true;    return false;  }  /**   * Returns a "set view" of this Map's entries. The set is backed by   * the Map, so changes in one show up in the other.  The set supports   * element removal, but not element addition.   * <p>   *   * <em>The semantics of this set, and of its contained entries, are   * different from the contract of Set and Map.Entry in order to make   * IdentityHashMap work.  This means that while you can compare these   * objects between IdentityHashMaps, comparing them with regular sets   * or entries is likely to have undefined behavior.</em>  The entries   * in this set are reference-based, rather than the normal object   * equality.  Therefore, <code>e1.equals(e2)</code> returns   * <code>e1.getKey() == e2.getKey() && e1.getValue() == e2.getValue()</code>,   * and <code>e.hashCode()</code> returns   * <code>System.identityHashCode(e.getKey()) ^   *       System.identityHashCode(e.getValue())</code>.   * <p>   *   * Note that the iterators for all three views, from keySet(), entrySet(),   * and values(), traverse the Map in the same sequence.   *   * @return a set view of the entries   * @see #keySet()   * @see #values()   * @see Map.Entry   */  public Set entrySet()  {    if (entries == null)      entries = new AbstractSet()      {        public int size()        {          return size;        }        public Iterator iterator()        {          return new IdentityIterator(ENTRIES);        }        public void clear()        {          IdentityHashMap.this.clear();        }        public boolean contains(Object o)        {          if (! (o instanceof Map.Entry))            return false;          Map.Entry m = (Map.Entry) o;          return m.getValue() == table[hash(m.getKey()) + 1];        }        public int hashCode()        {          return IdentityHashMap.this.hashCode();        }        public boolean remove(Object o)        {          if (! (o instanceof Map.Entry))            return false;          Object key = ((Map.Entry) o).getKey();          int h = hash(key);          if (table[h] == key)            {              size--;              modCount++;              table[h] = tombstone;              table[h + 1] = tombstone;              return true;            }          return false;        }      };    return entries;  }  /**   * Compares two maps for equality. This returns true only if both maps   * have the same reference-identity comparisons. While this returns   * <code>this.entrySet().equals(m.entrySet())</code> as specified by Map,   * this will not work with normal maps, since the entry set compares   * with == instead of .equals.   *   * @param o the object to compare to   * @return true if it is equal   */  public boolean equals(Object o)  {    // Why did Sun specify this one? The superclass does the right thing.    return super.equals(o);  }  /**   * Return the value in this Map associated with the supplied key, or   * <code>null</code> if the key maps to nothing.   *   * <p>NOTE: Since the value could also be null, you must use   * containsKey to see if this key actually maps to something.   * Unlike normal maps, this tests for the key with <code>entry ==   * key</code> instead of <code>entry == null ? key == null :   * entry.equals(key)</code>.   *   * @param key the key for which to fetch an associated value   * @return what the key maps to, if present   * @see #put(Object, Object)   * @see #containsKey(Object)   */  public Object get(Object key)  {    int h = hash(key);    return table[h] == key ? table[h + 1] : null;  }  /**   * Returns the hashcode of this map. This guarantees that two   * IdentityHashMaps that compare with equals() will have the same hash code,   * but may break with comparison to normal maps since it uses   * System.identityHashCode() instead of hashCode().   *   * @return the hash code   */  public int hashCode()  {    int hash = 0;    for (int i = table.length - 2; i >= 0; i -= 2)      {        Object key = table[i];        if (key == emptyslot || key == tombstone)          continue;        hash += (System.identityHashCode(key)                 ^ System.identityHashCode(table[i + 1]));      }    return hash;  }  /**   * Returns true if there are no key-value mappings currently in this Map   * @return <code>size() == 0</code>   */  public boolean isEmpty()  {    return size == 0;  }  /**   * Returns a "set view" of this Map's keys. The set is backed by the   * Map, so changes in one show up in the other.  The set supports   * element removal, but not element addition.   * <p>   *   * <em>The semantics of this set are different from the contract of Set   * in order to make IdentityHashMap work.  This means that while you can   * compare these objects between IdentityHashMaps, comparing them with   * regular sets is likely to have undefined behavior.</em>  The hashCode   * of the set is the sum of the identity hash codes, instead of the   * regular hashCodes, and equality is determined by reference instead   * of by the equals method.   * <p>   *   * @return a set view of the keys   * @see #values()   * @see #entrySet()   */  public Set keySet()  {    if (keys == null)      keys = new AbstractSet()      {        public int size()        {          return size;        }        public Iterator iterator()        {          return new IdentityIterator(KEYS);        }        public void clear()        {          IdentityHashMap.this.clear();        }        public boolean contains(Object o)        {          return containsKey(o);        }        public int hashCode()        {          int hash = 0;          for (int i = table.length - 2; i >= 0; i -= 2)            {              Object key = table[i];              if (key == emptyslot || key == tombstone)                continue;              hash += System.identityHashCode(key);            }          return hash;        }        public boolean remove(Object o)        {          int h = hash(o);          if (table[h] == o)            {              size--;              modCount++;              table[h] = tombstone;              table[h + 1] = tombstone;              return true;            }          return false;        }      };    return keys;

⌨️ 快捷键说明

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