001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.collections4.keyvalue; 018 019import java.util.Map; 020import java.util.Objects; 021 022/** 023 * Abstract Pair class to assist with creating correct 024 * {@link java.util.Map.Entry Map.Entry} implementations. 025 * 026 * @param <K> the type of keys 027 * @param <V> the type of mapped values 028 * @since 3.0 029 */ 030public abstract class AbstractMapEntry<K, V> extends AbstractKeyValue<K, V> implements Map.Entry<K, V> { 031 032 /** 033 * Constructs a new entry with the given key and given value. 034 * 035 * @param key the key for the entry, may be null 036 * @param value the value for the entry, may be null 037 */ 038 protected AbstractMapEntry(final K key, final V value) { 039 super(key, value); 040 } 041 042 /** 043 * Compares this {@code Map.Entry} with another {@code Map.Entry}. 044 * <p> 045 * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)} 046 * 047 * @param obj the object to compare to 048 * @return true if equal key and value 049 */ 050 @Override 051 public boolean equals(final Object obj) { 052 if (obj == this) { 053 return true; 054 } 055 if (!(obj instanceof Map.Entry)) { 056 return false; 057 } 058 final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj; 059 return Objects.equals(getKey(), other.getKey()) && 060 Objects.equals(getValue(), other.getValue()); 061 } 062 063 /** 064 * Gets a hashCode compatible with the equals method. 065 * <p> 066 * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()} 067 * 068 * @return a suitable hash code 069 */ 070 @Override 071 public int hashCode() { 072 return (getKey() == null ? 0 : getKey().hashCode()) ^ 073 (getValue() == null ? 0 : getValue().hashCode()); 074 } 075 076 /** 077 * Sets the value stored in this {@code Map.Entry}. 078 * <p> 079 * This {@code Map.Entry} is not connected to a Map, so only the 080 * local data is changed. 081 * 082 * @param value the new value 083 * @return the previous value 084 */ 085 @Override 086 public V setValue(final V value) { // NOPMD 087 return super.setValue(value); 088 } 089 090}