Codebase list libonemind-commons-java-java / 5c42640 src / java / org / onemind / commons / java / datastructure / SimpleNametable.java
5c42640

Tree @5c42640 (Download .tar.gz)

SimpleNametable.java @5c42640raw · history · blame

/*
 * Copyright (C) 2004 TiongHiang Lee
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not,  write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Email: thlee@onemindsoft.org
 */

package org.onemind.commons.java.datastructure;

import java.util.Collections;
import java.util.Map;
/**
 * A simple implementation of nametable
 * @author TiongHiang Lee (thlee@onemindsoft.org)
 */
public class SimpleNametable implements Nametable
{

    private final Map _table;

    /**
     * Constructor
     * @param m the name
     */
    public SimpleNametable(Map m)
    {
        _table = m;
    }

    /** 
     * {@inheritDoc}
     */
    public void declare(String name, Object value)
    {
        if (_table.containsKey(name))
        {
            throw new IllegalArgumentException("Variable '" + name + "' has been declared.");
        } else
        {
            _table.put(name, value);
        }
    }

    /** 
     * {@inheritDoc}
     */
    public Object assign(String name, Object value)
    {
        if (_table.containsKey(name))
        {
            return _table.put(name, value);
        } else
        {
            throw new IllegalArgumentException("Variable '" + name + "' has not been declared.");
        }
    }

    /** 
     * {@inheritDoc}
     */
    public boolean containsName(String name)
    {
        return _table.containsKey(name);
    }

    /** 
     * {@inheritDoc}
     */
    public Object access(String name)
    {
        if (containsName(name))
        {
            return _table.get(name);
        } else
        {
            throw new IllegalArgumentException("Varaible '" + name + "' has not been declared.");
        }
    }

    /** 
     * {@inheritDoc}
     */
    public void undeclare(String name)
    {
        //TODO: need declaration check?
        _table.remove(name);
    }
    
    public String toString()
    {
        return _table.toString();
    }
    
    /**
     * Return the name table as a map
     * @return unmodifiable map representation of the name table
     */
    public Map asMap()
    {
        return Collections.unmodifiableMap(_table);
    }
}