001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.keyvalue;
018
019import org.apache.commons.collections4.KeyValue;
020
021/**
022 * Abstract pair class to assist with creating {@code KeyValue}
023 * and {@link java.util.Map.Entry Map.Entry} implementations.
024 *
025 * @param <K> the type of keys
026 * @param <V> the type of values
027 * @since 3.0
028 */
029public abstract class AbstractKeyValue<K, V> implements KeyValue<K, V> {
030
031    /** The key */
032    private K key;
033    /** The value */
034    private V value;
035
036    /**
037     * Constructs a new pair with the specified key and given value.
038     *
039     * @param key  the key for the entry, may be null
040     * @param value  the value for the entry, may be null
041     */
042    protected AbstractKeyValue(final K key, final V value) {
043        this.key = key;
044        this.value = value;
045    }
046
047    /**
048     * Gets the key from the pair.
049     *
050     * @return the key
051     */
052    @Override
053    public K getKey() {
054        return key;
055    }
056
057    /**
058     * Gets the value from the pair.
059     *
060     * @return the value
061     */
062    @Override
063    public V getValue() {
064        return value;
065    }
066
067    protected K setKey(final K key) {
068        final K old = this.key;
069        this.key = key;
070        return old;
071    }
072
073    protected V setValue(final V value) {
074        final V old = this.value;
075        this.value = value;
076        return old;
077    }
078
079    /**
080     * Gets a debugging String view of the pair.
081     *
082     * @return a String view of the entry
083     */
084    @Override
085    public String toString() {
086        return new StringBuilder()
087            .append(getKey())
088            .append('=')
089            .append(getValue())
090            .toString();
091    }
092
093}