Linux 拨号vps windows公众号手机端

hashmap怎么清空所有元素

lewis 8年前 (2017-06-11) 阅读数 8 #程序编程
文章标签 hashmap

要清空一个 HashMap 中的所有元素,可以使用 HashMap 的 clear() 方法。

示例代码如下:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        
        // 添加元素到 HashMap
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
        
        System.out.println("HashMap before clearing: " + hashMap);
        
        // 清空 HashMap
        hashMap.clear();
        
        System.out.println("HashMap after clearing: " + hashMap);
    }
}

输出结果:

HashMap before clearing: {A=1, B=2, C=3}
HashMap after clearing: {}

在示例代码中,首先创建一个 HashMap,并向其中添加了三个元素。然后使用 clear() 方法清空 HashMap。最后输出清空前后的 HashMap 元素。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门