【Java】HashMap的简单使用(含小部分源码,get报错问题)
    		       		warning:
    		            这篇文章距离上次修改已过435天,其中的内容可能已经有所变动。
    		        
        		                
                
import java.util.HashMap;
 
public class HashMapExample {
    public static void main(String[] args) {
        // 创建HashMap实例
        HashMap<String, Integer> map = new HashMap<>();
 
        // 添加键值对
        map.put("apple", 10);
        map.put("banana", 20);
        map.put("cherry", 30);
 
        // 获取并打印apple的数量
        Integer appleCount = map.get("apple");
        System.out.println("appleCount: " + appleCount);
 
        // 获取并打印grape的数量(grape不存在,将返回null)
        Integer grapeCount = map.get("grape");
        System.out.println("grapeCount: " + grapeCount);
 
        // 检查键是否存在
        if (map.containsKey("apple")) {
            System.out.println("apple exists in the map");
        }
 
        // 获取所有的键
        for (String key : map.keySet()) {
            System.out.println("Key: " + key);
        }
 
        // 获取所有的值
        for (Integer value : map.values()) {
            System.out.println("Value: " + value);
        }
 
        // 删除一个键值对
        map.remove("banana");
 
        // 打印出修改后的map
        System.out.println("Modified map: " + map);
    }
}这段代码展示了如何创建一个HashMap,如何添加、获取、检查键的存在、遍历键和值、删除键值对,并处理了get方法可能返回null的情况。这是学习HashMap的基本用法和常见问题解决方法的一个很好的示例。
评论已关闭