/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.atea.nlptools.macroniser.util;

import java.util.HashMap;
import java.util.Map;

/**
 * A pool of objects. When the getCanonicalObject(Object) method is invoked, if
 * the pool contains an Object equal to this Object as determined by the
 * equals(Object) method, then the Object from the pool is returned. Otherwise,
 * the Object is added to the pool and a reference to this Object is returned.
 *
 * @author John Cocks
 */
public class Pool<T>
{
    private Map<T, T> pool;

    /**
     * Constructs a new Pool which is initially empty.
     */
    public Pool() {
        pool = new HashMap<T, T>();
    }

    /**
     * Returns a canonical representation of the Object.
     * @param obj The Object to pool.
     * @return The canonical representation of the Object.
     */
    public T getCanonicalObject(T obj)
    {
        if (pool.containsKey(obj))
        {
            return pool.get(obj);
        }
        else
        {
            pool.put(obj, obj);
            return obj;
        }
    }

    /**
     * Removes all pooled Objects from this Pool.
     */
    public void clear() {
        pool.clear();
    }
}
