我正在寻找Java中的KeyValuePair类。 因为java。util大量使用接口,没有提供具体的实现,只有Map。输入接口。

是否有可以导入的规范实现? 这是我讨厌实现100次的“水管工编程”类之一。


当前回答

Hashtable<String, Object>

它比java.util.Properties好,后者实际上是Hashtable<Object, Object>的扩展。

其他回答

类AbstractMap。SimpleEntry是通用的,可能很有用。

import java.util.Map;

public class KeyValue<K, V> implements Map.Entry<K, V>
{
    private K key;
    private V value;

    public KeyValue(K key, V value)
    {
        this.key = key;
        this.value = value;
    }

    public K getKey()
    {
        return this.key;
    }

    public V getValue()
    {
        return this.value;
    }

    public K setKey(K key)
    {
        return this.key = key;
    }

    public V setValue(V value)
    {
        return this.value = value;
    }
}

我最喜欢的是

HashMap<Type1, Type2>

您所要做的就是为Type1指定键的数据类型,为Type2指定值的数据类型。这是我在Java中见过的最常见的键值对象。

https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Android程序员可以使用BasicNameValuePair

更新:

BasicNameValuePair现在已弃用(API 22)。 使用Pair代替。

使用示例:

Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"

您可以轻松地创建自定义KeyValuePair类

public class Key<K, V>{

    K key;
    V value;

    public Key() {

    }

    public Key(K key, V  value) {
        this.key = key;
        this.value = value;
    }

    public void setValue(V value) {
        this.value = value;
    }
    public V getValue() {
        return value;
    }

    public void setKey(K key) {
        this.key = key;
    }
    public K getKey() {
        return key;
    }

}