使用java的hashmap.containskey()函数判断hashmap中是否包含指定键
在java中,hashmap是一种常用的数据结构,它以键值对的形式存储数据,其中每个键都是唯一的。当我们需要在hashmap中查找某个键是否存在时,可以使用containskey()函数来进行判断。
containskey()函数是hashmap类的成员函数,它的作用是判断hashmap中是否包含指定的键。它的函数签名如下:
public boolean containskey(object key)
该函数接受一个参数key,表示要查找的键。如果hashmap中包含该键,则返回true;否则,返回false。
下面是一个使用containskey()函数的示例代码:
import java.util.hashmap;
public class main {
public static void main(string[] args) { // 创建一个hashmap对象并添加一些键值对 hashmap<string, integer> hashmap = new hashmap<>(); hashmap.put("apple", 1); hashmap.put("banana", 2); hashmap.put("orange", 3); // 判断hashmap中是否含有指定的键 string key = "apple"; if (hashmap.containskey(key)) { system.out.println(key + " is in the hashmap"); } else { system.out.println(key + " is not in the hashmap"); } key = "pear"; if (hashmap.containskey(key)) { system.out.println(key + " is in the hashmap"); } else { system.out.println(key + " is not in the hashmap"); }}
}
运行上述代码,输出结果如下:
apple is in the hashmap
pear is not in the hashmap
在示例代码中,我们首先创建了一个hashmap对象hashmap,并使用put()函数向其中添加了三个键值对。然后,我们通过调用containskey()函数来判断hashmap中是否包含指定的键。
在第一个判断中,我们将key设为apple,因为该键存在于hashmap中,所以判断结果为true,打印apple is in the hashmap。
而在第二个判断中,我们将key设为pear,因为该键不存在于hashmap中,所以判断结果为false,打印pear is not in the hashmap。
总结一下,使用java的hashmap.containskey()函数可以方便地判断hashmap中是否包含指定的键。这可以帮助我们在需要查找某个键时,快速找到对应的值或者判断键是否存在,提高程序的效率和准确性。
以上就是使用java的hashmap.containskey()函数判断hashmap中是否包含指定键的详细内容。