Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map.containsValue — testing for a mapped value

Check whether any key maps to a given value, and see why the `WeakHashMap` example checks for a `null` value before calling `reachabilityFence(t3)`.

Version: Java SE 21

Syntax

boolean containsValue(Object value);

Map.containsValue is an instance method of java.util.Map<K, V>. It takes an Object, not a V. Under the interface contract, it returns true if Objects.equals(value, v) holds for at least one stored value v, and false otherwise. It neither identifies a matching key nor counts matches. IdentityHashMap deliberately departs from this contract and compares values with ==.

containsKey(key) looks for a key; containsValue(value) looks among the values. If the map permits null values, containsValue(null) detects an entry mapped to null, not a missing entry. For a disallowed null or an inappropriate type, an implementation may return false or throw NullPointerException or ClassCastException, respectively. ConcurrentHashMap throws NullPointerException for a null value query.

Value lookup typically takes time linear in the number of entries for most implementations: it may have to examine the entire map. Do not assume it is as fast as key lookup.

WeakHashMap permits null values and holds keys through weak references. When a key becomes weakly reachable, its entry can disappear as a result of garbage collection. Placing Reference.reachabilityFence(t3) after the check keeps the key object strongly reachable at least until that call completes. It does not trigger garbage collection or guarantee that the entry will disappear later.

Examples

import java.lang.ref.Reference;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
    public static void main(String[] args) {
        Map<Object, String> map = new WeakHashMap<>();
        Object t3 = new Object();
        map.put(t3, null);

        System.out.println(map.containsValue(null));
        System.out.println(map.containsKey(null));
        System.out.println(map.containsValue("ready"));
        Reference.reachabilityFence(t3);
    }
}

Result

true
false
false

The first line is `true` because `t3` maps to `null`. The second is `false` because `null` is not a key, and the third is `false` because no entry maps to `"ready"`.

Related lessons

  • Java · Lesson 18 · Advanced · Version: 2

Sources