我正在寻找Java中的KeyValuePair类.
由于java.util大量使用接口,因此没有提供具体实现,只有Map.Entry接口.
我可以导入一些规范的实现吗?这是我讨厌实施100倍的"管道工编程"课程之一.
Eya*_*der 232
文档AbstractMap.SimpleEntry是通用的,可能很有用.
kre*_*ker 98
Android程序员可以使用BasicNameValuePair
更新:
BasicNameValuePair现已弃用(API 22).改为使用Pair.
用法示例:
Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"
Run Code Online (Sandbox Code Playgroud)
rem*_*pod 42
Commons Lang的Pair类可能有所帮助:
Pair<String, String> keyValue = new ImmutablePair("key", "value");
Run Code Online (Sandbox Code Playgroud)
当然,你需要包含commons-lang.
Aar*_*son 13
对于可以实例化的任何两种类型的大多数简单键值配对,使用javafx.util.Pair就足够了.
Pair<Integer, String> myPair = new Pair<>(7, "Seven");
Integer key = myPair.getKey();
String value = myPair.getValue();
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我喜欢用
例子:
Properties props = new Properties();
props.setProperty("displayName", "Jim Wilson"); // (key, value)
String name = props.getProperty("displayName"); // => Jim Wilson
String acctNum = props.getProperty("accountNumber"); // => null
String nextPosition = props.getProperty("position", "1"); // => 1
Run Code Online (Sandbox Code Playgroud)
如果您熟悉哈希表,您就会对此非常熟悉
您可以轻松创建自定义 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
330143 次 |
| 最近记录: |