Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map access: key presence, lookup, and updates

Distinguish a missing key from a stored null, choose the right lookup method, and cache singleton instances only after construction succeeds.

Version: Java SE 21

Syntax

// Instance method declarations in java.util.Map<K, V>
boolean containsKey(Object key);
V get(Object key);
default V getOrDefault(Object key, V defaultValue) {
    V value = get(key);
    return (value != null || containsKey(key)) ? value : defaultValue;
}
V put(K key, V value);

In Java SE 21, Map.containsKey(Object key) tests whether the key has an entry, even if its value is null. Map.get(Object key) returns the stored value, or null if there is no entry. On maps that allow null values, get alone cannot tell those two cases apart.

Map.getOrDefault(Object key, V defaultValue) returns the fallback only when the key has no entry. A key mapped to null still returns null, and the lookup does not insert anything. In map.getOrDefault(key, factory()), factory() runs even on a hit: Java evaluates arguments before calling the method.

Map.put(K key, V value) adds or replaces an entry and returns the previous value. A null return can mean there was no entry or that the previous value was null. HashMap supports put and allows a null key and null values; not all maps do. An unsupported put throws UnsupportedOperationException, and storing a disallowed null throws NullPointerException. Depending on the implementation, a disallowed key or value type or property can cause ClassCastException or IllegalArgumentException, respectively. A lookup may reject a key of the wrong type with ClassCastException or a disallowed null key with NullPointerException.

In a single-threaded registry, keep factories separate from the cache of ready singletons. Check the cache first; on a miss, look up and call the registered factory. Cache the instance only after it has been fully constructed and checked to be non-null. If the factory throws, nothing is cached. Calls for the same key share an instance within one registry, not globally. With multiple threads, coordinate the whole check–construct–store sequence; changing the map type alone does not make that sequence atomic.

Examples

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

public class Main {
    record Service(String name) {}

    static final class Registry {
        private final Map<String, Supplier<Service>> registrations = new HashMap<>();
        private final Map<String, Service> ready = new HashMap<>();

        Registry() {
            registrations.put("report", () -> {
                System.out.println("construct report");
                return new Service("report");
            });
        }

        Service resolve(String key) {
            if (ready.containsKey(key)) {
                return ready.get(key);
            }
            Supplier<Service> factory = registrations.get(key);
            if (factory == null) {
                throw new IllegalArgumentException("Unknown service: " + key);
            }
            Service service = Objects.requireNonNull(factory.get(), "Factory returned null");
            ready.put(key, service);
            return service;
        }
    }

    public static void main(String[] args) {
        Map<String, String> labels = new HashMap<>();
        labels.put("unset", null);
        System.out.println("containsKey: " + labels.containsKey("unset") + "/" + labels.containsKey("missing"));
        System.out.println("get: " + labels.get("unset") + "/" + labels.get("missing"));
        System.out.println("getOrDefault: " + labels.getOrDefault("unset", "fallback") + "/"
                + labels.getOrDefault("missing", "fallback"));
        labels.put("unset", "configured");
        System.out.println("put returned: " + labels.put("unset", "updated"));
        System.out.println("current value: " + labels.get("unset"));

        Registry registry = new Registry();
        Service first = registry.resolve("report");
        Service second = registry.resolve("report");
        System.out.println("same instance: " + (first == second));
    }
}

Result

containsKey: true/false
get: null/null
getOrDefault: null/fallback
put returned: configured
current value: updated
construct report
same instance: true

The first three lines compare an entry mapped to `null` with a missing entry. Then `put` returns `configured` but leaves `updated` in the map. The `construct report` message appears once, and `==` confirms both resolutions return the same instance.

Related lessons

  • Java · Lesson 59 · Advanced · Version: 2

Sources