1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.collections4.keyvalue;
18
19 import org.apache.commons.collections4.KeyValue;
20
21 /**
22 * Abstract pair class to assist with creating {@code KeyValue}
23 * and {@link java.util.Map.Entry Map.Entry} implementations.
24 *
25 * @param <K> the type of keys
26 * @param <V> the type of values
27 * @since 3.0
28 */
29 public abstract class AbstractKeyValue<K, V> implements KeyValue<K, V> {
30
31 /** The key */
32 private K key;
33 /** The value */
34 private V value;
35
36 /**
37 * Constructs a new pair with the specified key and given value.
38 *
39 * @param key the key for the entry, may be null
40 * @param value the value for the entry, may be null
41 */
42 protected AbstractKeyValue(final K key, final V value) {
43 this.key = key;
44 this.value = value;
45 }
46
47 /**
48 * Gets the key from the pair.
49 *
50 * @return the key
51 */
52 @Override
53 public K getKey() {
54 return key;
55 }
56
57 /**
58 * Gets the value from the pair.
59 *
60 * @return the value
61 */
62 @Override
63 public V getValue() {
64 return value;
65 }
66
67 /**
68 * Sets the key.
69 *
70 * @param key The key.
71 * @return The previous key.
72 */
73 protected K setKey(final K key) {
74 final K old = this.key;
75 this.key = key;
76 return old;
77 }
78
79 /**
80 * Sets the value.
81 *
82 * @param value The value.
83 * @return The previous value.
84 */
85 protected V setValue(final V value) {
86 final V old = this.value;
87 this.value = value;
88 return old;
89 }
90
91 /**
92 * Gets a debugging String view of the pair.
93 *
94 * @return a String view of the entry
95 */
96 @Override
97 public String toString() {
98 return new StringBuilder()
99 .append(getKey())
100 .append('=')
101 .append(getValue())
102 .toString();
103 }
104
105 }