/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.lang.collection;

import nuts.core.lang.builder.EqualsBuilder;
import nuts.core.lang.builder.HashCodeBuilder;

import java.util.Map;
import java.util.Map.Entry;


/**
 */
public class KeyValue<K, V> implements Entry<K, V> {

	/** The key */
	protected K key;
	
	/** The value */
	protected V value;

	/**
	 * Constructs a new pair with the specified key and given value.
	 * 
	 * @param key the key for the entry, may be null
	 * @param value the value for the entry, may be null
	 */
	public KeyValue(K key, V value) {
		super();
		this.key = key;
		this.value = value;
	}

	/**
	 * Gets the key from the pair.
	 * 
	 * @return the key
	 */
	public K getKey() {
		return key;
	}

	/**
	 * Gets the value from the pair.
	 * 
	 * @return the value
	 */
	public V getValue() {
		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	public V setValue(V value) {
		V old = value;
		this.value = value;
		return old;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(key).append(value).hashCode();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Map.Entry)) {
			return false;
		}

		Map.Entry rhs = (Map.Entry)obj;
		return new EqualsBuilder().append(key, rhs.getKey()).append(value, rhs.getValue()).isEquals();
	}

	/**
	 * Gets a debugging String view of the pair.
	 * 
	 * @return a String view of the entry
	 */
	@Override
	public String toString() {
		return new StringBuilder().append(getKey()).append('=').append(getValue()).toString();
	}
}
