001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.modeshape.common.collection;
017
018import java.util.Map;
019import org.modeshape.common.annotation.Immutable;
020import org.modeshape.common.util.HashCode;
021import org.modeshape.common.util.ObjectUtil;
022
023/**
024 * An immutable {@link java.util.Map.Entry} implementation.
025 * 
026 * @param <K> the key type
027 * @param <V> the value type
028 */
029@Immutable
030public class ImmutableMapEntry<K, V> implements Map.Entry<K, V> {
031    private final K key;
032    private final V value;
033
034    public ImmutableMapEntry( K key,
035                              V value ) {
036        this.key = key;
037        this.value = value;
038    }
039
040    public ImmutableMapEntry( Map.Entry<K, V> entry ) {
041        this.key = entry.getKey();
042        this.value = entry.getValue();
043    }
044
045    @Override
046    public K getKey() {
047        return key;
048    }
049
050    @Override
051    public V getValue() {
052        return value;
053    }
054
055    @Override
056    public V setValue( V newValue ) {
057        throw new UnsupportedOperationException();
058    }
059
060    @Override
061    public int hashCode() {
062        return HashCode.compute(key, value);
063    }
064
065    @Override
066    public boolean equals( Object obj ) {
067        if (obj == this) return true;
068        if (obj instanceof Map.Entry) {
069            Map.Entry<?, ?> that = (Map.Entry<?, ?>)obj;
070            if (!ObjectUtil.isEqualWithNulls(this.getKey(), that.getKey())) return false;
071            if (!ObjectUtil.isEqualWithNulls(this.getValue(), that.getValue())) return false;
072            return true;
073        }
074        return false;
075    }
076
077    @Override
078    public String toString() {
079        return "" + this.key + " = " + this.getValue();
080    }
081}