我正在寻找Java中的KeyValuePair类。 因为java。util大量使用接口,没有提供具体的实现,只有Map。输入接口。
是否有可以导入的规范实现? 这是我讨厌实现100次的“水管工编程”类之一。
我正在寻找Java中的KeyValuePair类。 因为java。util大量使用接口,没有提供具体的实现,只有Map。输入接口。
是否有可以导入的规范实现? 这是我讨厌实现100次的“水管工编程”类之一。
当前回答
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;
}
}
其他回答
类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;
}
}
Hashtable<String, Object>
它比java.util.Properties好,后者实际上是Hashtable<Object, Object>的扩展。
使用javafx.util.Pair对于任何两种可以实例化的类型的大多数简单键-值对已经足够了。
Pair<Integer, String> myPair = new Pair<>(7, "Seven");
Integer key = myPair.getKey();
String value = myPair.getValue();
我最喜欢的是
HashMap<Type1, Type2>
您所要做的就是为Type1指定键的数据类型,为Type2指定值的数据类型。这是我在Java中见过的最常见的键值对象。
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html