简体   繁体   中英

TreeMap allowing null key

I am searching for a TreeMap that allows one null key. 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.
I have been searching for this map for quite a while, but all I found was TreeMap which does not allow null keys.

Does Java have any sorted maps that allow one null key?

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM