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