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 * https://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 java.util.Map.Entry;
20
21 import org.apache.commons.collections4.KeyValue;
22 /**
23 * Abstract pair class to assist with creating {@code KeyValue}
24 * and {@link Entry Map.Entry} implementations.
25 *
26 * @param <K> The type of keys
27 * @param <V> The type of values
28 * @since 3.0
29 */
30 public abstract class AbstractKeyValue<K, V> implements KeyValue<K, V> {
31
32 /** The key */
33 private K key;
34
35 /** The value */
36 private V value;
37
38 /**
39 * Constructs a new pair with the specified key and given value.
40 *
41 * @param key The key for the entry, may be null
42 * @param value The value for the entry, may be null
43 */
44 protected AbstractKeyValue(final K key, final V value) {
45 this.key = key;
46 this.value = value;
47 }
48
49 /**
50 * Gets the key from the pair.
51 *
52 * @return The key
53 */
54 @Override
55 public K getKey() {
56 return key;
57 }
58
59 /**
60 * Gets the value from the pair.
61 *
62 * @return The value
63 */
64 @Override
65 public V getValue() {
66 return value;
67 }
68
69 /**
70 * Sets the key.
71 *
72 * @param key The key.
73 * @return The previous key.
74 */
75 protected K setKey(final K key) {
76 final K old = this.key;
77 this.key = key;
78 return old;
79 }
80
81 /**
82 * Sets the value.
83 *
84 * @param value The value.
85 * @return The previous value.
86 */
87 protected V setValue(final V value) {
88 final V old = this.value;
89 this.value = value;
90 return old;
91 }
92
93 /**
94 * Gets a debugging String view of the pair.
95 *
96 * @return A String view of the entry
97 */
98 @Override
99 public String toString() {
100 return new StringBuilder()
101 .append(getKey())
102 .append('=')
103 .append(getValue())
104 .toString();
105 }
106
107 }