English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java HashMap clear() usage and example

Java HashMap Methods

Java HashMap clear() method removes all keys from the hashmap/Value pairs.

The syntax of the clear() method is:

hashmap.clear();

Parameters of clear()

The clear() method does not take any parameters.

Return value of clear()

The clear() method does not return any value. Instead, it changes the hashmap.

Example: Java HashMap clear()

import java.util.HashMap;
class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> numbers = new HashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("HashMap: ", + numbers);
        //Remove all mappings from HashMap
        numbers.clear();
        System.out.println("HashMap after clear(): ", + numbers);
    }
}

Output Result

HashMap: {One=1, Two=2, Three=3}
HashMap after clear(): {}

In the above example, we created a hashmap named numbers. Here, we use the clear() method to remove allKey/Value.

NoteWe can useHashMap remove()The method removes a single item from the hash map.

Reinitialize HashMap

In Java, we can implement the functionality of the clear() method by reinitializing the hashmap. For example

import java.util.HashMap;
class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> numbers = new HashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("HashMap: ", + numbers);
        //Reinitialize hashmap
        numbers = new HashMap<>();
        System.out.println("new HashMap: ", + numbers);
    }
}

Output Result

HashMap: {One=1, Two=2, Three=3}
new HashMap: {}

In the above example, we created a hashmap named numbers. The hashmap contains3elements. Note this line,

numbers = new HashMap<>();

In this case, the process will not delete all items from the hashmap. Instead, it creates a new hashmap and assigns the new hashmap to the number. And, the old hashmap is deleted by the garbage collector.

NoteThe working way of reinitializing HashMap and clear() method may be similar. However, they are two different processes.

Java HashMap Methods