View Javadoc
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      protected K setKey(final K key) {
68          final K old = this.key;
69          this.key = key;
70          return old;
71      }
72  
73      protected V setValue(final V value) {
74          final V old = this.value;
75          this.value = value;
76          return old;
77      }
78  
79      /**
80       * Gets a debugging String view of the pair.
81       *
82       * @return a String view of the entry
83       */
84      @Override
85      public String toString() {
86          return new StringBuilder()
87              .append(getKey())
88              .append('=')
89              .append(getValue())
90              .toString();
91      }
92  
93  }