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;
20 import java.util.Map.Entry;
21 import java.util.Objects;
22
23 /**
24 * Abstract Pair class to assist with creating correct
25 * {@link Entry Map.Entry} implementations.
26 *
27 * @param <K> The type of keys
28 * @param <V> The type of mapped values
29 * @since 3.0
30 */
31 public abstract class AbstractMapEntry<K, V> extends AbstractKeyValue<K, V> implements Map.Entry<K, V> {
32
33 /**
34 * Constructs a new entry with the given key and given value.
35 *
36 * @param key The key for the entry, may be null
37 * @param value The value for the entry, may be null
38 */
39 protected AbstractMapEntry(final K key, final V value) {
40 super(key, value);
41 }
42
43 /**
44 * Compares this {@code Map.Entry} with another {@code Map.Entry}.
45 * <p>
46 * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)}
47 *
48 * @param obj The object to compare to
49 * @return true if equal key and value
50 */
51 @Override
52 public boolean equals(final Object obj) {
53 if (obj == this) {
54 return true;
55 }
56 if (!(obj instanceof Map.Entry)) {
57 return false;
58 }
59 final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
60 return Objects.equals(getKey(), other.getKey()) &&
61 Objects.equals(getValue(), other.getValue());
62 }
63
64 /**
65 * Gets a hashCode compatible with the equals method.
66 * <p>
67 * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()}
68 *
69 * @return A suitable hash code
70 */
71 @Override
72 public int hashCode() {
73 return (getKey() == null ? 0 : getKey().hashCode()) ^
74 (getValue() == null ? 0 : getValue().hashCode());
75 }
76
77 /**
78 * Sets the value stored in this {@code Map.Entry}.
79 * <p>
80 * This {@code Map.Entry} is not connected to a Map, so only the
81 * local data is changed.
82 *
83 * @param value The new value
84 * @return The previous value
85 */
86 @Override
87 public V setValue(final V value) { // NOPMD
88 return super.setValue(value);
89 }
90
91 }