identityhashmap.java

来自「java源代码 请看看啊 提点宝贵的意见」· Java 代码 · 共 1,168 行 · 第 1/3 页

JAVA
1,168 行
字号
                        System.arraycopy(tab, deletedSlot,                                          newTable, 0, remaining);                        traversalTable = newTable;                        index = 0;                    }                    tab[d] = item;                    tab[d + 1] = tab[i + 1];                    tab[i] = null;                    tab[i + 1] = null;                    d = i;                }            }        }    }      private class KeyIterator extends IdentityHashMapIterator {        public Object next() {            return unmaskNull(traversalTable[nextIndex()]);        }    }    private class ValueIterator extends IdentityHashMapIterator {        public Object next() {            return traversalTable[nextIndex() + 1];        }    }    /**     * Since we don't use Entry objects, we use the Iterator     * itself as an entry.     */    private class EntryIterator extends IdentityHashMapIterator                                 implements Map.Entry    {        public Object next() {            nextIndex();             return this;        }        public Object getKey() {            // Provide a better exception than out of bounds index            if (lastReturnedIndex < 0)                throw new IllegalStateException("Entry was removed");                            return unmaskNull(traversalTable[lastReturnedIndex]);        }        public Object getValue() {            // Provide a better exception than out of bounds index            if (lastReturnedIndex < 0)                throw new IllegalStateException("Entry was removed");            return traversalTable[lastReturnedIndex+1];        }        public Object setValue(Object value) {            // It would be mean-spirited to proceed here if remove() called             if (lastReturnedIndex < 0)                throw new IllegalStateException("Entry was removed");            Object oldValue = traversalTable[lastReturnedIndex+1];            traversalTable[lastReturnedIndex+1] = value;            // if shadowing, force into main table            if (traversalTable != IdentityHashMap.this.table)                put(traversalTable[lastReturnedIndex], value);            return oldValue;        }        public boolean equals(Object o) {            if (!(o instanceof Map.Entry))                return false;            Map.Entry e = (Map.Entry)o;            return e.getKey()   == getKey() &&                   e.getValue() == getValue();        }        public int hashCode() {            return System.identityHashCode(getKey()) ^                   System.identityHashCode(getValue());        }        public String toString() {            return getKey() + "=" + getValue();        }    }    // Views    /**     * This field is initialized to contain an instance of the entry set     * view the first time this view is requested.  The view is stateless,     * so there's no reason to create more than one.     */    private transient Set entrySet = null;    /**     * Returns an identity-based 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.  If the map is modified while an iteration     * over the set is in progress, the results of the iteration are     * undefined.  The set supports element removal, which removes the     * corresponding mapping from the map, via the <tt>Iterator.remove</tt>,     * <tt>Set.remove</tt>, <tt>removeAll</tt> <tt>retainAll</tt>, and     * <tt>clear</tt> methods.  It does not support the <tt>add</tt> or     * <tt>addAll</tt> methods.     *     * <p><b>While the object returned by this method implements the     * <tt>Set</tt> interface, it does <i>not</i> obey <tt>Set's</tt> general     * contract.  Like its backing map, the set returned by this method     * defines element equality as reference-equality rather than     * object-equality.  This affects the behavior of its <tt>contains</tt>,     * <tt>remove</tt>, <tt>containsAll</tt>, <tt>equals</tt>, and     * <tt>hashCode</tt> methods.</b>     *     * <p>The <tt>equals</tt> method of the returned set returns <tt>true</tt>     * only if the specified object is a set containing exactly the same     * object references as the returned set.  The symmetry and transitivity     * requirements of the <tt>Object.equals</tt> contract may be violated if     * the set returned by this method is compared to a normal set.  However,     * the <tt>Object.equals</tt> contract is guaranteed to hold among sets     * returned by this method.</b>     *     * <p>The <tt>hashCode</tt> method of the returned set returns the sum of     * the <i>identity hashcodes</i> of the elements in the set, rather than     * the sum of their hashcodes.  This is mandated by the change in the     * semantics of the <tt>equals</tt> method, in order to enforce the     * general contract of the <tt>Object.hashCode</tt> method among sets     * returned by this method.     *     * @return an identity-based set view of the keys contained in this map.     * @see Object#equals(Object)     * @see System#identityHashCode(Object)     */    public Set keySet() {        Set ks = keySet;        if (ks != null)            return ks;        else            return keySet = new KeySet();    }    private class KeySet extends AbstractSet {        public Iterator iterator() {            return new KeyIterator();        }        public int size() {            return size;        }        public boolean contains(Object o) {            return containsKey(o);        }        public boolean remove(Object o) {            int oldSize = size;            IdentityHashMap.this.remove(o);            return size != oldSize;        }        /*         * Must revert from AbstractSet's impl to AbstractCollection's, as         * the former contains an optimization that results in incorrect         * behavior when c is a smaller "normal" (non-identity-based) Set.         */        public boolean removeAll(Collection c) {            boolean modified = false;            for (Iterator i = iterator(); i.hasNext(); ) {                if(c.contains(i.next())) {                    i.remove();                    modified = true;                }            }            return modified;        }        public void clear() {            IdentityHashMap.this.clear();        }        public int hashCode() {            int result = 0;            for (Iterator i = iterator(); i.hasNext(); )                result += System.identityHashCode(i.next());            return result;        }    }    /**     * <p>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.  If the map is modified while an     * iteration over the collection is in progress, the results of the     * iteration are undefined.  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> methods.     * It does not support the <tt>add</tt> or <tt>addAll</tt> methods.     *     * <p><b>While the object returned by this method implements the     * <tt>Collection</tt> interface, it does <i>not</i> obey     * <tt>Collection's</tt> general contract.  Like its backing map,     * the collection returned by this method defines element equality as     * reference-equality rather than object-equality.  This affects the     * behavior of its <tt>contains</tt>, <tt>remove</tt> and     * <tt>containsAll</tt> methods.</b>     *     * @return a collection view of the values contained in this map.     */    public Collection values() {        Collection vs = values;        if (vs != null)            return vs;        else             return values = new Values();    }    private class Values extends AbstractCollection {        public Iterator iterator() {            return new ValueIterator();        }        public int size() {            return size;        }        public boolean contains(Object o) {            return containsValue(o);        }        public boolean remove(Object o) {            for (Iterator i = iterator(); i.hasNext(); ) {                if (i.next() == o) {                    i.remove();                    return true;                }            }            return false;        }        public void clear() {            IdentityHashMap.this.clear();        }    }    /**     * Returns a set view of the mappings contained in this map.  Each element     * in the returned set is a reference-equality-based <tt>Map.Entry</tt>.     * The set is backed by the map, so changes to the map are reflected in     * the set, and vice-versa.  If the map is modified while an iteration     * over the set is in progress, the results of the iteration are     * undefined.  The set supports element removal, which removes the     * corresponding mapping from the map, via the <tt>Iterator.remove</tt>,     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and     * <tt>clear</tt> methods.  It does not support the <tt>add</tt> or     * <tt>addAll</tt> methods.     *     * <p>Like the backing map, the <tt>Map.Entry</tt> objects in the set     * returned by this method define key and value equality as     * reference-equality rather than object-equality.  This affects the     * behavior of the <tt>equals</tt> and <tt>hashCode</tt> methods of these     * <tt>Map.Entry</tt> objects.  A reference-equality based <tt>Map.Entry     * e</tt> is equal to an object <tt>o</tt> if and only if <tt>o</tt> is a     * <tt>Map.Entry</tt> and <tt>e.getKey()==o.getKey() &&     * e.getValue()==o.getValue()</tt>.  To accommodate these equals     * semantics, the <tt>hashCode</tt> method returns     * <tt>System.identityHashCode(e.getKey()) ^     * System.identityHashCode(e.getValue())</tt>.     *     * <p><b>Owing to the reference-equality-based semantics of the     * <tt>Map.Entry</tt> instances in the set returned by this method,     * it is possible that the symmetry and transitivity requirements of     * the {@link Object#equals(Object)} contract may be violated if any of     * the entries in the set is compared to a normal map entry, or if     * the set returned by this method is compared to a set of normal map     * entries (such as would be returned by a call to this method on a normal     * map).  However, the <tt>Object.equals</tt> contract is guaranteed to     * hold among identity-based map entries, and among sets of such entries.     * </b>     *     * @return a set view of the identity-mappings contained in this map.     */    public Set entrySet() {        Set es = entrySet;        if (es != null)             return es;        else            return entrySet = new EntrySet();    }    private class EntrySet extends AbstractSet {        public Iterator iterator() {            return new EntryIterator();        }        public boolean contains(Object o) {            if (!(o instanceof Map.Entry))                return false;            Map.Entry entry = (Map.Entry)o;            return containsMapping(entry.getKey(), entry.getValue());        }        public boolean remove(Object o) {            if (!(o instanceof Map.Entry))                return false;            Map.Entry entry = (Map.Entry)o;            return removeMapping(entry.getKey(), entry.getValue());        }        public int size() {            return size;        }        public void clear() {            IdentityHashMap.this.clear();        }        /*         * Must revert from AbstractSet's impl to AbstractCollection's, as         * the former contains an optimization that results in incorrect         * behavior when c is a smaller "normal" (non-identity-based) Set.         */        public boolean removeAll(Collection c) {            boolean modified = false;            for (Iterator i = iterator(); i.hasNext(); ) {                if(c.contains(i.next())) {                    i.remove();                    modified = true;                }            }            return modified;        }        public Object[] toArray() {            Collection c = new ArrayList(size());            for (Iterator i = iterator(); i.hasNext(); )                c.add(new AbstractMap.SimpleEntry((Map.Entry) i.next()));            return c.toArray();        }        public Object[] toArray(Object a[]) {            Collection c = new ArrayList(size());            for (Iterator i = iterator(); i.hasNext(); )                c.add(new AbstractMap.SimpleEntry((Map.Entry) i.next()));            return c.toArray(a);        }    }    /**     * Save the state of the <tt>IdentityHashMap</tt> instance to a stream     * (i.e., serialize it).     *     * @serialData The <i>size</i> of the HashMap (the number of key-value     *	        mappings) (<tt>int</tt>), followed by the key (Object) and     *          value (Object) for each key-value mapping represented by the     *          IdentityHashMap.  The key-value mappings are emitted in no     *          particular order.     */    private void writeObject(java.io.ObjectOutputStream s)        throws java.io.IOException  {        // Write out and any hidden stuff        s.defaultWriteObject();        // Write out size (number of Mappings)        s.writeInt(size);        // Write out keys and values (alternating)        Object[] tab = table;        for (int i = 0; i < tab.length; i += 2) {            Object key = tab[i];            if (key != null) {                s.writeObject(unmaskNull(key));                s.writeObject(tab[i + 1]);            }        }    }    /**     * Reconstitute the <tt>IdentityHashMap</tt> instance from a stream (i.e.,     * deserialize it).     */    private void readObject(java.io.ObjectInputStream s)        throws java.io.IOException, ClassNotFoundException  {        // Read in any hidden stuff        s.defaultReadObject();            // Read in size (number of Mappings)        int size = s.readInt();        // Allow for 33% growth (i.e., capacity is >= 2* size()).        init(capacity((size*4)/3));        // 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);        }    }}

⌨️ 快捷键说明

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