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    /**
068     * Sets the key.
069     *
070     * @param key The key.
071     * @return The previous key.
072     */
073    protected K setKey(final K key) {
074        final K old = this.key;
075        this.key = key;
076        return old;
077    }
078
079    /**
080     * Sets the value.
081     *
082     * @param value The value.
083     * @return The previous value.
084     */
085    protected V setValue(final V value) {
086        final V old = this.value;
087        this.value = value;
088        return old;
089    }
090
091    /**
092     * Gets a debugging String view of the pair.
093     *
094     * @return a String view of the entry
095     */
096    @Override
097    public String toString() {
098        return new StringBuilder()
099            .append(getKey())
100            .append('=')
101            .append(getValue())
102            .toString();
103    }
104
105}