[英]TreeMap allowing null key
I am searching for a TreeMap
that allows one null
key.我正在寻找一个允许一个null
键的TreeMap
。 What I need is a sorted Map<Long,String>
where I can insert one null
key representing the default value: If the map does not contain the specified key, the value associated with the null
key will be used.我需要的是一个已排序的Map<Long,String>
,我可以在其中插入一个表示默认值的null
键:如果映射不包含指定的键,则将使用与null
键关联的null
。
I have been searching for this map for quite a while, but all I found was TreeMap
which does not allow null
keys.我一直在寻找这张地图很长一段时间,但我发现的只是TreeMap
,它不允许null
键。
Does Java have any sorted maps that allow one null
key? Java 是否有任何允许一个null
键的排序映射?
You could perhaps write your own.你也许可以自己写。 Something like this might work with some tinkering.像这样的事情可能需要一些修补。
static class MapWithDefault<K, V> extends TreeMap<K, V> {
private V dflt;
@Override
public V get(Object key) {
V v = super.get(key);
return v == null ? dflt : v;
}
@Override
public V put(K key, V value) {
if (key == null) {
V was = dflt;
dflt = value;
return was;
}
return super.put(key, value);
}
public void setDflt(V dflt) {
this.dflt = dflt;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.