A java.util.Map implementation using reference values : Map « Collections Data Structure « Java






A java.util.Map implementation using reference values

         
/**********************************************************************
Copyright (c) 2002 Mike Martin (TJDO) and others. All rights reserved.
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.
 

Contributors:
2002 Kelly Grizzle (TJDO)
2003 Andy Jefferson - commented
    ...
**********************************************************************/


import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/**
 * A <code>java.util.Map</code> implementation using reference values.
 *
 * <p>The values are stored in the map as references.  If the garbage collector
 * clears the reference, the corresponding key is automatically removed from the
 * map.
 *
 * @see java.lang.ref.Reference
 * @version $Revision: 1.3 $ 
 */
public abstract class ReferenceValueMap implements Map, Cloneable
{
    private HashMap map;
    private ReferenceQueue reaped = new ReferenceQueue();

    /**
     * Default Constructor.
     **/
    public ReferenceValueMap()
    {
        map = new HashMap();
    }

    /**
     * Constructor taking initial capacity.
     * @param initial_capacity Initial Capacity of HashMap
     **/
    public ReferenceValueMap(int initial_capacity)
    {
        map = new HashMap(initial_capacity);
    }

    /**
     * Constructor taking initial capacity and load factor.
     * @param initial_capacity Initial Capacity of HashMap
     * @param load_factor      Load Factor of HashMap
     **/
    public ReferenceValueMap(int initial_capacity,float load_factor)
    {
        map = new HashMap(initial_capacity, load_factor);
    }

    /**
     * Constructor taking initial Map.
     * @param m Map to initial with.
     **/
    public ReferenceValueMap(Map m)
    {
        map = new HashMap();
        putAll(m);
    }

    /**
     * Clone method.
     * @return Clone of this object.
     **/
    public Object clone()
    {
        reap();

        ReferenceValueMap rvm = null;
        
        try
        {
            rvm = (ReferenceValueMap)super.clone();
        }
        catch (CloneNotSupportedException e)
        {
            // Do nothing
        }

        rvm.map = (HashMap)map.clone(); // to preserve initialCapacity, loadFactor
        rvm.map.clear();
        rvm.reaped = new ReferenceQueue();
        rvm.putAll(entrySet());

        return rvm;
    }

    /**
     * References returned by <code>newValueReference</code> must implement
     * this interface to provide the corresponding map key for the value.
     */
    public interface ValueReference
    {
        /**
         * Returns the key associated with the value referenced by this
         * <code>Reference</code> object.
         * @return The Key
         */
        Object getKey();
    }

    /**
     * Returns a new <code>Reference</code> object to be inserted into the map.
     * Subclasses must implement this method to construct <code>Reference</code>
     * objects of the desired type (e.g. <code>SoftReference</code>, etc.).
     *
     * @param key   The key that will be inserted.
     * @param value The associated value to be referenced.
     * @param queue The <code>ReferenceQueue</code> with which to register the
     *              new <code>Reference</code> object.
     * @return The new ValueReference
     */
    protected abstract ValueReference newValueReference(Object key, Object value, ReferenceQueue queue);

    /**
     * Method to add an object to the Map.
     * @param key Key for object
     * @param value Value of object
     * @return The Object.
     **/ 
    public Object put(Object key, Object value)
    {
        reap();
        return map.put(key, newValueReference(key, value, reaped));
    }

    /**
     * Method to add the contents of a Map.
     * @param m Map
     **/ 
    public void putAll(Map m)
    {
        putAll(m.entrySet());
    }

    /**
     * Method to add the contents of a Set.
     * @param entrySet The Set
     **/
    private void putAll(Set entrySet)
    {
        Iterator i = entrySet.iterator();

        while (i.hasNext())
        {
            Map.Entry entry = (Map.Entry)i.next();
            put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * Method to get a value for a key.
     * @param key The Key
     * @return The Value
     **/
    public Object get(Object key)
    {
        reap();
        Reference ref = (Reference)map.get(key);

        Object value = ref == null ? null : ref.get();

        return value;
    }

    /**
     * Method to empty the HashMap.
     **/
    public void clear()
    {
        reap();
        map.clear();
    }

    /**
     * Accessor for the size of the HashMap.
     * @return The size
     **/
    public int size()
    {
        reap();
        return map.size();
    }

    /**
     * Accessor for whether the Map contains the specified Key
     * @param obj The key
     * @return Whether the key exists
     **/
    public boolean containsKey(Object obj)
    {
        reap();
        return map.containsKey(obj);
    }

    /**
     * Accessor for whether the Map contains the specified value.
     * @param obj The value
     * @return Whether the Map contains the value.
     **/
    public boolean containsValue(Object obj)
    {
        reap();

        if (obj != null)
        {
            Iterator i = map.values().iterator();

            while (i.hasNext())
            {
                Reference ref = (Reference)i.next();

                if (obj.equals(ref.get()))
                {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Accessor for whether the Map is empty.
     * @return Whether the Map is empty.
     **/
    public boolean isEmpty()
    {
        reap();
        return map.isEmpty();
    }

    /**
     * Accessor for the Set of keys in the Map.
     * @return The Set of keys
     **/
    public Set keySet()
    {
        reap();
        return map.keySet();
    }

    /**
     * Accessor for the values from the Map.
     * @return The Values.
     **/
    public Collection values()
    {
        reap();

        Collection c = map.values();
        Iterator i = c.iterator();
        ArrayList l = new ArrayList(c.size());

        while (i.hasNext())
        {
            Reference ref = (Reference)i.next();
            Object obj = ref.get();

            if (obj != null)
            {
                l.add(obj);
            }
        }

        return Collections.unmodifiableList(l);
    }

    /**
     * Accessor for the entry set.
     * @return The Set.
     **/
    public Set entrySet()
    {
        reap();

        Set s = map.entrySet();
        Iterator i = s.iterator();
        HashMap m = new HashMap(s.size());

        while (i.hasNext())
        {
            Map.Entry entry = (Map.Entry)i.next();
            Reference ref = (Reference)entry.getValue();
            Object obj = ref.get();

            if (obj != null)
            {
                m.put(entry.getKey(), obj);
            }
        }

        return Collections.unmodifiableSet(m.entrySet());
    }

    /**
     * Method to remove an object for the specified key.
     * @param key The Key
     * @return The Object removed 
     **/
    public Object remove(Object key)
    {
        reap();
        return map.remove(key);
    }

    /**
     * Hashcode generator for this object.
     * @return The Hashcode
     **/
    public int hashCode()
    {
        reap();
        return map.hashCode();
    }

    /**
     * Equality operator.
     * @param o THe object to compare against.
     * @return Whether it is equal.
     **/
    public boolean equals(Object o)
    {
        reap();
        return map.equals(o);
    }

    /**
     * Utility method to reap objects.
     **/
    public void reap()
    {
        ValueReference ref;

        while ((ref = (ValueReference)reaped.poll()) != null)
        {
            map.remove(ref.getKey());
        }
    }
}

   
    
    
    
    
    
    
    
    
  








Related examples in the same category

1.Creating and storing arrays in a map
2.Sort based on the values
3.Get a key from value with an HashMap
4.Retrieve environment variables (JDK1.5)
5.Creating a Type-Specific Map: creates a map whose keys are Integer objects and values are String objects.
6.A map declared to hold objects of a type T can also hold objects that extend from T
7.A value retrieved from a type-specific collection does not need to be casted
8.Map techniques.
9.Create an array containing the keys in a map
10.Create an array containing the values in a map
11.Creating a Hash Table
12.Creating a Map That Retains Order-of-Insertion
13.Automatically Removing an Unreferenced Element from a Hash Table
14.Creating a Type-Specific Map [5.0]
15.Use Iterator to loop through the HashMap class
16.Create type specific collections
17.Convert Properties into Map
18.Utility method that return a String representation of a map. The elements will be represented as "key = value"
19.Utility method that return a String representation of a map. The elements will be represented as "key = value" (tab)
20.This program demonstrates the use of a map with key type String and value type Employee
21.Format a Map
22.A Map implementation that dumps its content when memory runs low.
23.A Map that stores the values in files within a directory.
24.Map List
25.Multi Value Map Array List
26.Multi Value Map Linked HashSet
27.An object that maps keys to values, and values back to keys.
28.LRU Map
29.A map acts like array.
30.Order Retaining Map
31.BinaryMap class implements a map from objects to integer objects where the only value is the integer with value 1.
32.A space-optimized map for associating char keys with values.
33.A Map implementation that grows to a fixed size and then retains only a fixed number of the highest (largest) keys.
34.Class which creates mapping between keys and a list of values.
35.A map of values by class.
36.History Map
37.Sorts map by values in ascending order.
38.Map from a given key to a list of values
39.Map from a given key to a set of values
40.Class which keeps a set of values and assigns each value a unique positive index.
41.Array Map
42.Array map
43.An ArrayMap is a very inefficient map type that is more robust in dealing with changes to its keys than other maps.
44.This Map stores it's keys as strings in upper case, null and duplicate keys are not allowed
45.Map to string
46.A simple class that stores key Strings as char[]'s in a hash table.