Java 集合 HashMap从键中获取值

来源:这里教程网 时间:2026-02-17 20:13:35 作者:

在提供键时从HashMap获取值的程序。

示例

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);  }}

输出:

The Value mapped to Key 4 is:DDThe Value mapped to Key 5 is:null

注意:在上面的程序中,键 5 没有映射到任何值,因此get()方法返回null,但是您不能使用此方法来检查HashMap中是否存在某个键,因为返回值null不一定表示映射不包含键;映射也可能将键明确映射为null。您必须使用containsKey()方法来检查HashMap中键是否存在。

相关推荐