JDK

KeyValueHolderクラス

キーと値を保持するだけのMap.Entry<K,V>インタフェースを実装したクラスであるが,パッケージプライベートなクラスであるため,ユーザは基本的に使用できない(リフレクションでやれなくはないが,そこまでやるなら自作した方が早い)。

インスタンス変数としては,keyとvalueがある。コンストラクタはKeyValueHolder(K k, V v)だけが定義されている。

setValue(V value)メソッドを呼び出すとUnsupportedOperationExceptionがスローされる。equals(Object o)メソッドは,KeyValueHolderクラスかそのサブクラスならば,キーと値が一致すればtrue,それ以外はfalseを返す。

hashCode()メソッドではkeyのハッシュコードとvalueのハッシュコードの排他的論理和を算出して返す。toString()hashCode()メソッドではkeyとvalueを”=”で連結して返している。

/*
 * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package java.util;
import jdk.internal.vm.annotation.Stable;
final class KeyValueHolder<K,V> implements Map.Entry<K,V> {
    @Stable
    final K key;
    @Stable
    final V value;
    KeyValueHolder(K k, V v) {
        key = Objects.requireNonNull(k);
        value = Objects.requireNonNull(v);
    }
    @Override
    public K getKey() {
        return key;
    }
    @Override
    public V getValue() {
        return value;
    }
    @Override
    public V setValue(V value) {
        throw new UnsupportedOperationException("not supported");
    }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry<?,?> e = (Map.Entry<?,?>)o;
        return key.equals(e.getKey()) && value.equals(e.getValue());
    }
    @Override
    public int hashCode() {
        return key.hashCode() ^ value.hashCode();
    }
    @Override
    public String toString() {
        return key + "=" + value;
    }
}