Project

General

Profile

Using Map's putIfAbsent method of implementors is risky...

Added by Komorek, Kamil over 4 years ago

Damn, what a find.

I've code:

return this.cachedConnections.putIfAbsent(
        whateverKey,
        new FooBar(foo)
);

Looking at default Map implementation:

default V putIfAbsent(K key, V value) {
    V v = get(key);
    if (v == null) {
        v = put(key, value);
    }

    return v;
}

Logic. If null put and return / a'ka defaultObject.

However I'm getting NullPointerException while trying to use returned object... why?!

Solution because putIfAbsent implementation in eg. HashMap which I'm using is totally different... and returns null/old value in that call.


Comments