多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# `HashMap` - 从键中获取值 > 原文: [https://beginnersbook.com/2014/08/hashmap-get-value-from-key-example/](https://beginnersbook.com/2014/08/hashmap-get-value-from-key-example/) #### 描述 在提供键时从`HashMap`获取值的程序。 #### 示例 ```java import java.util.HashMap; class HashMapDemo{ public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //add elements to HashMap hmap.put(1, "AA"); hmap.put(2, "BB"); hmap.put(3, "CC"); hmap.put(4, "DD"); // Getting values from HashMap String val=hmap.get(4); System.out.println("The Value mapped to Key 4 is:"+ val); /* Here Key "5" is not mapped to any value so this * operation returns null. */ String val2=hmap.get(5); System.out.println("The Value mapped to Key 5 is:"+ val2); } } ``` **输出:** ```java The Value mapped to Key 4 is:DD The Value mapped to Key 5 is:null ``` 注意:在上面的程序中,键 5 没有映射到任何值,因此`get()`方法返回`null`,但是您不能使用此方法来检查`HashMap`中是否存在某个键,因为返回值`null`不一定表示映射不包含键;映射也可能将键明确映射为`null`。您必须使用`containsKey()`方法来检查`HashMap`中键[是否存在](https://beginnersbook.com/2014/07/java-check-if-a-particular-key-exists-in-hashmap-example/)。