您的位置:首页 > 产品设计 > UI/UE

Java - How to create new Entry (key, value)

2016-12-12 21:11 309 查看
I'd like to create new item that similarly to Util.Map.Entry that will contain the structure key, value.

The problem is that I can't instantiate a Map.Entry because it's an interface.
Does anyone know how to create a new generic key/value object for Map.Entry?

You can just implement the Map.Entry<K, V> interface yourself:

java中如何创建Entry对象?因为Map.Entry是一个接口,所以无法直接new。

答案:需要自己去创建一个对象,实现Map.Entry接口

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());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐