Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashMap clear() Method

Java HashMap clear() Method

Java HashMap Java HashMap

The clear() method is used to remove all key/value pairs from the specified HashMap.

The syntax of the clear() method is:


hashmap.clear()

**Note:** hashmap is an object of the HashMap class.

Parameter Description:

Return Value

No value is returned.

Example

The following example demonstrates the use of the clear() method:

Example

import

java.util.HashMap

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

        HashMap

<

Integer

, String

sites

=

new

HashMap

<>

(

)

;

        sites.

put

(

1

,

"Google"

)

;

        sites.

put

(

2

,

"Runoob"

)

;

        sites.

put

(

3

,

"Taobao"

)

;

       

System

.

out

.

println

(

"HashMap: "

sites

)

;

       

// Remove all mappings from the HashMap

        sites.

clear

(

)

;

       

System

.

out

.

println

(

"After using the clear() method: "

sites

)

;

   

}

}

The output of the above program is:


HashMap: {1=Google, 2=Runoob, 3=Taobao}
使用 clear() 方法后: {}

In the above example, we created a HashMap named sites, and then used the clear() method to remove all key/value pairs of sites.

Note: we can also use Java HashMap remove() Methodto remove the key/value pair corresponding to a key.

Reinitialize the HashMap

In Java, we can also delete all key/value pairs by reinitializing the HashMap, for example:

Example

import

java.util.HashMap

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

        HashMap

<

Integer

, String

sites

=

new

HashMap

<>

(

)

;

        sites.

put

(

1

,

"Google"

)

;

        sites.

put

(

2

,

"Runoob"

)

;

        sites.

put

(

3

,

"Taobao"

)

;

       

System

.

out

.

println

(

"HashMap: "

sites

)

;

       

// Remove all mappings from the HashMap

       

// Reinitialize the hashmap

        sites

=

new

HashMap

<>

(

)

;

       

System

.

out

.

println

(

"New HashMap: "

sites

)

;

   

}

}

The output of the above program is:


HashMap: {1=Google, 2=Runoob, 3=Taobao}
新的 HashMap: {}

In the above example, we created a HashMap named sites that contains 3 elements. Note this line:


numbers = new HashMap<>();

The above code will not remove all items from the HashMap; instead, it creates a new HashMap, assigns it to sites, and the original key/value pairs of sites will be reclaimed and removed by the garbage collector.

Java HashMap Java HashMap