Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.HashMap: practical reference

util.HashMap: practical reference: HashMap<K,V> is a hash-table Map implementation that permits one null key and null values without guaranteeing encounter order.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.HashMap

HashMap<K,V> is a hash-table Map implementation that permits one null key and null values without guaranteeing encounter order.

Use it as the default mutable map when keys have stable equals and hashCode and iteration order is irrelevant.

It is not synchronized; mutating key state used by equals or hashCode can make an existing entry effectively unreachable.

Basic operations are constant-time on average with well-dispersed hashes, but iteration costs size plus capacity and crossing the load factor triggers costly rehashing.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var map = new java.util.HashMap<String, Integer>();
        map.put("a", 1);
        map.put("a", 2);
        System.out.println(map.size());
        System.out.println(map.get("a"));
    }
}

Result

1
2

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources