Java.util.HashMap 类

java.util.HashMap.clear()方法用于清除map的所有键值映射。此方法使map为空,大小为零。

语法

public void clear()
  • 1

参数

不需要参数。

返回值

void 类型。

异常

示例:

In在下面的示例中, java.util.HashMap.clear() 方法用于清除给定映射的所有键值映射。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建哈希图
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //填充map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //打印map
    System.out.println("Before applying clear() method.");
    System.out.println("MyMap contains: " + MyMap);

    //清除所有映射
    MyMap.clear();

    //再次打印map
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MyMap contains: " + MyMap);   
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

上述代码的输出将是:

Before applying clear() method.
MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo}

After applying clear() method.
MyMap contains: {}
  • 1
  • 2
  • 3
  • 4
  • 5