containsKey() 函数判断 map 中是否存在某个键?
在 Java 中,Map 是一种非常有用的数据结构,它可以用来存储一组键值对(key-value pairs),其中每个键都是 的。通过将一个键和相应的值相关联,可以将多个相关联的值保存在同一个数据结构中,并且可以快速地通过键来查找相应的值。
常用的 Map 接口实现类有 HashMap、TreeMap、LinkedHashMap 等等。无论是哪一种实现类,都提供了一个 containsKey() 方法,这个方法是用来判断 Map 中是否存在某个键的。
containsKey() 方法的返回值是一个布尔值,如果 Map 中包含指定的键,那么返回 true,否则返回 false。例如,以下代码片段演示了如何使用 containsKey() 方法检查一个 HashMap 是否包含指定的键:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
if (map.containsKey("apple")) {
System.out.println("map contains key 'apple'.");
}
if (map.containsKey("orange")) {
System.out.println("map contains key 'orange'.");
} else {
System.out.println("map does not contain key 'orange'.");
}
上面的代码中,首先创建了一个 HashMap,并向其中添加两个键值对。接着,使用 containsKey() 方法检查该 Map 是否包含指定的键。 个条件返回 true,因为 Map 中确实包含键 "apple";第二个条件返回 false,因为 Map 中不包含键 "orange"。
还有一种方法可以完成相同的任务,那就是使用 get() 方法,例如:
if (map.get("apple") != null) {
System.out.println("map contains key 'apple'.");
}
if (map.get("orange") != null) {
System.out.println("map contains key 'orange'.");
} else {
System.out.println("map does not contain key 'orange'.");
}
上面这段代码使用了 get() 方法来获取 Map 中指定键的值,如果此时返回值为 null,则说明 Map 中不存在该键。使用 get() 方法比使用 containsKey() 方法多了一步获取值的操作,可能会带来一些额外的开销,但是两种方法的效果是一样的。
需要注意的是,Map 中的键必须是 的,如果尝试向 Map 中添加一个键值对,其中键已经存在,那么旧值将被新值替换。例如,以下代码演示了这一点:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("apple", 3); // 替换旧值
if (map.containsKey("apple")) {
System.out.println("map contains key 'apple'");
System.out.println("the value of 'apple' is " + map.get("apple"));
}
注意最后一行代码,因为使用 put() 方法替换了键 "apple" 对应的值,所以键 "apple" 的值变成了 3,而不是原来的 1。
总之,containsKey() 方法是 Map 接口中非常有用的一个方法,它可以用来检查 Map 中是否包含指定键,并且可以帮助我们编写更加简洁高效的代码。
