Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2003 The Visigoth Software Society. 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 acknowledgement:
  *       "This product includes software developed by the
  *        Visigoth Software Society (http://www.visigoths.org/)."
  *    Alternately, this acknowledgement may appear in the software itself,
  *    if and wherever such third-party acknowledgements normally appear.
  *
  * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the 
  *    project contributors may be used to endorse or promote products derived
  *    from this software without prior written permission. For written
  *    permission, please contact visigoths@visigoths.org.
  *
  * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
  *    nor may "FreeMarker" or "Visigoth" appear in their names
  *    without prior written permission of the Visigoth Software Society.
  *
  * 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 VISIGOTH SOFTWARE SOCIETY 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.
  * ====================================================================
  *
  * This software consists of voluntary contributions made by many
  * individuals on behalf of the Visigoth Software Society. For more
  * information on the Visigoth Software Society, please see
  * http://www.visigoths.org/
  */
 
 package freemarker.ext.util;
 
 import java.util.Map;
 import java.util.Set;

A variant of java.util.HashMap that uses java.lang.System.identityHashCode(java.lang.Object) for hashing, and reference comparison instead of java.lang.Object.equals(java.lang.Object). Note that this applies only to keys, and not to values, i.e. containsValue(java.lang.Object) still uses java.lang.Object.equals(java.lang.Object).

Author(s):
Attila Szegedi
 
 public class IdentityHashMap
     extends AbstractMap
     implements MapCloneablejava.io.Serializable
 {
 
     public static final long serialVersionUID = 362498820763181265L;
    
The hash table data.
 
     private transient Entry table[];

    
The total number of mappings in the hash table.
 
     private transient int count;

    
The table is rehashed when its size exceeds this threshold. (The value of this field is (int)(capacity * loadFactor).)

Serial:
 
     private int threshold;

    
The load factor for the hashtable.

Serial:
    private float loadFactor;

    
The number of times this IdentityHashMap has been structurally modified Structural modifications are those that change the number of mappings in the IdentityHashMap or otherwise modify its internal structure (e.g., rehash). This field is used to make iterators on Collection-views of the IdentityHashMap fail-fast. (See ConcurrentModificationException).
    private transient int modCount = 0;

    
Constructs a new, empty map with the specified initial capacity and the specified load factor.

Parameters:
initialCapacity the initial capacity of the IdentityHashMap.
loadFactor the load factor of the IdentityHashMap
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive.
    public IdentityHashMap(int initialCapacityfloat loadFactor)
    {
        if (initialCapacity < 0)
            throw new IllegalArgumentException(
                "Illegal Initial Capacity: " + initialCapacity);
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException(
                "Illegal Load factor: " + loadFactor);
        if (initialCapacity == 0)
            initialCapacity = 1;
        this. = loadFactor;
         = new Entry[initialCapacity];
         = (int) (initialCapacity * loadFactor);
    }

    
Constructs a new, empty map with the specified initial capacity and default load factor, which is 0.75.

Parameters:
initialCapacity the initial capacity of the IdentityHashMap.
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero.
    public IdentityHashMap(int initialCapacity)
    {
        this(initialCapacity, 0.75f);
    }

    
Constructs a new, empty map with a default capacity and load factor, which is 0.75.
    public IdentityHashMap()
    {
        this(11, 0.75f);
    }

    
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 11 (whichever is greater), and a default load factor, which is 0.75.

Parameters:
t the map whose mappings are to be placed in this map.
    public IdentityHashMap(Map t)
    {
        this(Math.max(2 * t.size(), 11), 0.75f);
        putAll(t);
    }

    
Returns the number of key-value mappings in this map.

Returns:
the number of key-value mappings in this map.
    public int size()
    {
        return ;
    }

    
Returns true if this map contains no key-value mappings.

Returns:
true if this map contains no key-value mappings.
    public boolean isEmpty()
    {
        return  == 0;
    }

    
Returns true if this map maps one or more keys to the specified value.

Parameters:
value value whose presence in this map is to be tested.
Returns:
true if this map maps one or more keys to the specified value.
    public boolean containsValue(Object value)
    {
        Entry tab[] = ;
        if (value == null)
        {
            for (int i = tab.lengthi-- > 0;)
                for (Entry e = tab[i]; e != nulle = e.next)
                    if (e.value == null)
                        return true;
        }
        else
        {
            for (int i = tab.lengthi-- > 0;)
                for (Entry e = tab[i]; e != nulle = e.next)
                    if (value.equals(e.value))
                        return true;
        }
        return false;
    }

    
Returns true if this map contains a mapping for the specified key.

Parameters:
key key whose presence in this Map is to be tested.
Returns:
true if this map contains a mapping for the specified key.
    public boolean containsKey(Object key)
    {
        Entry tab[] = ;
        if (key != null)
        {
            int hash = System.identityHashCode(key);
            int index = (hash & 0x7FFFFFFF) % tab.length;
            for (Entry e = tab[index]; e != nulle = e.next)
                if (e.hash == hash && key == e.key)
                    return true;
        }
        else
        {
            for (Entry e = tab[0]; e != nulle = e.next)
                if (e.key == null)
                    return true;
        }
        return false;
    }

    
Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Parameters:
key key whose associated value is to be returned.
Returns:
the value to which this map maps the specified key.
    public Object get(Object key)
    {
        Entry tab[] = ;
        if (key != null)
        {
            int hash = System.identityHashCode(key);
            int index = (hash & 0x7FFFFFFF) % tab.length;
            for (Entry e = tab[index]; e != nulle = e.next)
                if ((e.hash == hash) && key == e.key)
                    return e.value;
        }
        else
        {
            for (Entry e = tab[0]; e != nulle = e.next)
                if (e.key == null)
                    return e.value;
        }
        return null;
    }

    
Rehashes the contents of this map into a new IdentityHashMap instance with a larger capacity. This method is called automatically when the number of keys in this map exceeds its capacity and load factor.
    private void rehash()
    {
        int oldCapacity = .;
        Entry oldMap[] = ;
        int newCapacity = oldCapacity * 2 + 1;
        Entry newMap[] = new Entry[newCapacity];
        ++;
         = (int) (newCapacity * );
         = newMap;
        for (int i = oldCapacityi-- > 0;)
        {
            for (Entry old = oldMap[i]; old != null;)
            {
                Entry e = old;
                old = old.next;
                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = newMap[index];
                newMap[index] = e;
            }
        }
    }

    
Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.

Parameters:
key key with which the specified value is to be associated.
value value to be associated with the specified key.
Returns:
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the IdentityHashMap previously associated null with the specified key.
    public Object put(Object keyObject value)
    {
        // Makes sure the key is not already in the IdentityHashMap.
        Entry tab[] = ;
        int hash = 0;
        int index = 0;
        if (key != null)
        {
            hash = System.identityHashCode(key);
            index = (hash & 0x7FFFFFFF) % tab.length;
            for (Entry e = tab[index]; e != nulle = e.next)
            {
                if ((e.hash == hash) && key == e.key)
                {
                    Object old = e.value;
                    e.value = value;
                    return old;
                }
            }
        }
        else
        {
            for (Entry e = tab[0]; e != nulle = e.next)
            {
                if (e.key == null)
                {
                    Object old = e.value;
                    e.value = value;
                    return old;
                }
            }
        }
        ++;
        if ( >= )
        {
            // Rehash the table if the threshold is exceeded
            rehash();
            tab = ;
            index = (hash & 0x7FFFFFFF) % tab.length;
        }
        // Creates the new entry.
        Entry e = new Entry(hashkeyvaluetab[index]);
        tab[index] = e;
        ++;
        return null;
    }

    
Removes the mapping for this key from this map if present.

Parameters:
key key whose mapping is to be removed from the map.
Returns:
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key.
    public Object remove(Object key)
    {
        Entry tab[] = ;
        if (key != null)
        {
            int hash = System.identityHashCode(key);
            int index = (hash & 0x7FFFFFFF) % tab.length;
            for (Entry e = tab[index], prev = null;
                e != null;
                prev = ee = e.next)
            {
                if ((e.hash == hash) && key == e.key)
                {
                    ++;
                    if (prev != null)
                        prev.next = e.next;
                    else
                        tab[index] = e.next;
                    --;
                    Object oldValue = e.value;
                    e.value = null;
                    return oldValue;
                }
            }
        }
        else
        {
            for (Entry e = tab[0], prev = null;
                e != null;
                prev = ee = e.next)
            {
                if (e.key == null)
                {
                    ++;
                    if (prev != null)
                        prev.next = e.next;
                    else
                        tab[0] = e.next;
                    --;
                    Object oldValue = e.value;
                    e.value = null;
                    return oldValue;
                }
            }
        }
        return null;
    }

    
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.

Parameters:
t Mappings to be stored in this map.
    public void putAll(Map t)
    {
        Iterator i = t.entrySet().iterator();
        while (i.hasNext())
        {
            Map.Entry e = (Map.Entryi.next();
            put(e.getKey(), e.getValue());
        }
    }

    
Removes all mappings from this map.
    public void clear()
    {
        Entry tab[] = ;
        ++;
        for (int index = tab.length; --index >= 0;)
            tab[index] = null;
         = 0;
    }

    
Returns a shallow copy of this IdentityHashMap instance: the keys and values themselves are not cloned.

Returns:
a shallow copy of this map.
    public Object clone()
    {
        try
        {
            IdentityHashMap t = (IdentityHashMapsuper.clone();
            t.table = new Entry[.];
            for (int i = .i-- > 0;)
            {
                t.table[i] =
                    ([i] != null) ? (Entry[i].clone() : null;
            }
            t.keySet = null;
            t.entrySet = null;
            t.values = null;
            t.modCount = 0;
            return t;
        }
        catch (CloneNotSupportedException e)
        {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError();
        }
    }
    // Views
    private transient Set keySet = null;
    private transient Set entrySet = null;
    private 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 Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Returns:
a set view of the keys contained in this map.
    public Set keySet()
    {
        if ( == null)
        {
             = new AbstractSet()
            {
                public Iterator iterator()
                {
                    return getHashIterator();
                }
                public int size()
                {
                    return ;
                }
                public boolean contains(Object o)
                {
                    return containsKey(o);
                }
                public boolean remove(Object o)
                {
                    int oldSize = ;
                    IdentityHashMap.this.remove(o);
                    return  != oldSize;
                }
                public void clear()
                {
                    IdentityHashMap.this.clear();
                }
            };
        }
        return ;
    }

    
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 Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Returns:
a collection view of the values contained in this map.
    public Collection values()
    {
        if ( == null)
        {
             = new AbstractCollection()
            {
                public Iterator iterator()
                {
                    return getHashIterator();
                }
                public int size()
                {
                    return ;
                }
                public boolean contains(Object o)
                {
                    return containsValue(o);
                }
                public void clear()
                {
                    IdentityHashMap.this.clear();
                }
            };
        }
        return ;
    }

    
Returns a collection view of the mappings contained in this map. Each element in the returned collection is a Map.Entry. 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 Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Returns:
a collection view of the mappings contained in this map.
See also:
java.util.Map.Entry
    public Set entrySet()
    {
        if ( == null)
        {
             = new AbstractSet()
            {
                public Iterator iterator()
                {
                    return getHashIterator();
                }
                public boolean contains(Object o)
                {
                    if (!(o instanceof Map.Entry))
                        return false;
                    Map.Entry entry = (Map.Entryo;
                    Object key = entry.getKey();
                    Entry tab[] = ;
                    int hash = (key == null ? 0 : System.identityHashCode(key));
                    int index = (hash & 0x7FFFFFFF) % tab.length;
                    for (Entry e = tab[index]; e != nulle = e.next)
                        if (e.hash == hash && e.equals(entry))
                            return true;
                    return false;
                }
                public boolean remove(Object o)
                {
                    if (!(o instanceof Map.Entry))
                        return false;
                    Map.Entry entry = (Map.Entryo;
                    Object key = entry.getKey();
                    Entry tab[] = ;
                    int hash = (key == null ? 0 : System.identityHashCode(key));
                    int index = (hash & 0x7FFFFFFF) % tab.length;
                    for (Entry e = tab[index], prev = null;
                        e != null;
                        prev = ee = e.next)
                    {
                        if (e.hash == hash && e.equals(entry))
                        {
                            ++;
                            if (prev != null)
                                prev.next = e.next;
                            else
                                tab[index] = e.next;
                            --;
                            e.value = null;
                            return true;
                        }
                    }
                    return false;
                }
                public int size()
                {
                    return ;
                }
                public void clear()
                {
                    IdentityHashMap.this.clear();
                }
            };
        }
        return ;
    }
    private Iterator getHashIterator(int type)
    {
        if ( == 0)
        {
            return ;
        }
        else
        {
            return new HashIterator(type);
        }
    }

    
IdentityHashMap collision list entry.
    private static class Entry implements Map.Entry
    {
        int hash;
        Object key;
        Object value;
        Entry next;
        Entry(int hashObject keyObject valueEntry next)
        {
            this. = hash;
            this. = key;
            this. = value;
            this. = next;
        }
        protected Object clone()
        {
            return new Entry(
                ,
                ,
                ,
                ( == null ? null : (Entry.clone()));
        }
        // Map.Entry Ops
        public Object getKey()
        {
            return ;
        }
        public Object getValue()
        {
            return ;
        }
        public Object setValue(Object value)
        {
            Object oldValue = this.;
            this. = value;
            return oldValue;
        }
        public boolean equals(Object o)
        {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entryo;
            return ( == e.getKey())
                && ( == null
                    ? e.getValue() == null
                    : .equals(e.getValue()));
        }
        public int hashCode()
        {
            return  ^ ( == null ? 0 : .hashCode());
        }
        public String toString()
        {
            return  + "=" + ;
        }
    }
    // Types of Iterators
    private static final int KEYS = 0;
    private static final int VALUES = 1;
    private static final int ENTRIES = 2;
    private static EmptyHashIterator emptyHashIterator =
        new EmptyHashIterator();
    private static class EmptyHashIterator implements Iterator
    {
        EmptyHashIterator()
        {
        }
        public boolean hasNext()
        {
            return false;
        }
        public Object next()
        {
            throw new NoSuchElementException();
        }
        public void remove()
        {
            throw new IllegalStateException();
        }
    }
    private class HashIterator implements Iterator
    {
        Entry[] table = IdentityHashMap.this.;
        int index = .;
        Entry entry = null;
        Entry lastReturned = null;
        int type;

        
The modCount value that the iterator believes that the backing List should have. If this expectation is violated, the iterator has detected concurrent modification.
        private int expectedModCount = ;
        HashIterator(int type)
        {
            this. = type;
        }
        public boolean hasNext()
        {
            Entry e = ;
            int i = ;
            Entry t[] = ;
            /* Use locals for faster loop iteration */
            while (e == null && i > 0)
                e = t[--i];
             = e;
             = i;
            return e != null;
        }
        public Object next()
        {
            if ( != )
                throw new ConcurrentModificationException();
            Entry et = ;
            int i = ;
            Entry t[] = ;
            /* Use locals for faster loop iteration */
            while (et == null && i > 0)
                et = t[--i];
             = et;
             = i;
            if (et != null)
            {
                Entry e =  = ;
                 = e.next;
                return  ==  ? e.key : ( ==  ? e.value : e);
            }
            throw new NoSuchElementException();
        }
        public void remove()
        {
            if ( == null)
                throw new IllegalStateException();
            if ( != )
                throw new ConcurrentModificationException();
            Entry[] tab = IdentityHashMap.this.;
            int index = (. & 0x7FFFFFFF) % tab.length;
            for (Entry e = tab[index], prev = null;
                e != null;
                prev = ee = e.next)
            {
                if (e == )
                {
                    ++;
                    ++;
                    if (prev == null)
                        tab[index] = e.next;
                    else
                        prev.next = e.next;
                    --;
                     = null;
                    return;
                }
            }
            throw new ConcurrentModificationException();
        }
    }

    
Save the state of the IdentityHashMap instance to a stream (i.e., serialize it).

SerialData:
The capacity of the IdentityHashMap (the length of the bucket array) is emitted (int), followed by the size of the IdentityHashMap (the number of key-value mappings), 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 the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        // Write out number of buckets
        s.writeInt(.);
        // Write out size (number of Mappings)
        s.writeInt();
        // Write out keys and values (alternating)
        for (int index = . - 1; index >= 0; index--)
        {
            Entry entry = [index];
            while (entry != null)
            {
                s.writeObject(entry.key);
                s.writeObject(entry.value);
                entry = entry.next;
            }
        }
    }

    
Reconstitute the IdentityHashMap instance from a stream (i.e., deserialize it).
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException
    {
        // 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();
         = new Entry[numBuckets];
        // Read in size (number of Mappings)
        int size = s.readInt();
        // Read the keys and values, and put the mappings in the IdentityHashMap
        for (int i = 0; i < sizei++)
        {
            Object key = s.readObject();
            Object value = s.readObject();
            put(keyvalue);
        }
    }
    int capacity()
    {
        return .;
    }
    float loadFactor()
    {
        return ;
    }
New to GrepCode? Check out our FAQ X