Java - 如何创建新条目(键、值) [英] Java - How to create new Entry (key, value)
本文介绍了Java - 如何创建新条目(键、值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建类似于 Util.Map.Entry
的新项目,它将包含结构 key
, value
.
I'd like to create new item that similarly to Util.Map.Entry
that will contain the structure key
, value
.
问题是我无法实例化 Map.Entry
因为它是一个接口.
The problem is that I can't instantiate a Map.Entry
because it's an interface.
有谁知道如何为 Map.Entry 创建一个新的通用键/值对象?
Does anyone know how to create a new generic key/value object for Map.Entry?
推荐答案
你可以自己实现 Map.Entry
接口:
You can just implement the Map.Entry<K, V>
interface yourself:
import java.util.Map;
final class MyEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public MyEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
}
然后使用它:
Map.Entry<String, Object> entry = new MyEntry<String, Object>("Hello", 123);
System.out.println(entry.getKey());
System.out.println(entry.getValue());
这篇关于Java - 如何创建新条目(键、值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文