containsKey()
方法的语法是:
hashmap.containsKey(Object key)
这里,
hashmap 是
HashMap
类的对象。
包含Key() 参数
containsKey()
方法接受一个参数。
containsKey() 返回值
返回true
如果指定的 key 的映射存在于 hashmap 中
如果哈希映射中不存在指定key的映射,则返回false
示例 1: Java HashMap containsKey()
import java.util.HashMap; class Main { public static void main(String[] args){ // create a HashMap HashMap<String, String> details = new HashMap<>(); // add mappings to HashMap details.put("Name", "Programiz"); details.put("Domain", "programiz.com"); details.put("Location", "Nepal"); System.out.println("Programiz Details: \n" + details); // check if key Domain is present if(details.containsKey("Domain")) { System.out.println("Domain name is present in the Hashmap."); } } }
输出
Programiz Details: {Domain=programiz.com, Name=Programiz, Location=Nepal} Domain name is present in the Hashmap.
在上面的例子中,我们创建了一个哈希图。注意表达式,
details.containsKey("Domain") // returns true
这里,hashmap 包含键
Domain 的映射。因此,
containsKey()
方法返回
true
并执行
if
块内的语句。
示例 2: 如果 Key 不存在,则向 HashMap 添加条目
import java.util.HashMap; class Main { public static void main(String[] args){ // create a HashMap HashMap<String, String> countries = new HashMap<>(); // add mappings to HashMap countries.put("USA", "Washington"); countries.put("Australia", "Canberra"); System.out.println("HashMap:\n" + countries); // check if key Spain is present if(!countries.containsKey("Spain")) { // add entry if key already not present countries.put("Spain", "Madrid"); } System.out.println("Updated HashMap:\n" + countries); } }
输出
HashMap: {USA=Washington, Australia=Canberra} Updated HashMap: {USA=Washington, Australia=Canberra, Spain=Madrid}
在上面的例子中,注意表达式,
if(!countries.containsKey("Spain")) {..}
在这里,我们使用了
containsKey()
方法来检查
Spain 的映射是否存在于 hashmap 中。由于我们使用了否定符号(
!
),如果方法返回
false
,则执行
if
块。
因此,只有在 hashmap 中没有指定
key 的映射时,才会添加新映射。
注意: 我们也可以使用 HashMap putIfAbsent() 方法来执行相同的任务。