Use the containsValue() method of the Hashtable class in Java to determine whether the value exists in the hash table
The hash table is a data structure that stores data in the form of key-value pairs. It provides a Efficient data access. The Hashtable class in Java is a data structure that implements a hash table. It provides a variety of methods for operating data in the hash table.
In actual development, we often encounter the need to determine whether a certain value exists in the hash table. The Hashtable class in Java provides the containsValue() method to determine whether the specified value exists in the value of the hash table. The declaration of this method is as follows:
public boolean containsValue(Object value)
Among them, the value parameter is the value to be judged.
Below we use a code example to demonstrate how to use the containsValue() method to determine whether a value exists in the hash table.
import java.util.Hashtable; public class Main { public static void main(String[] args) { // 创建一个Hashtable对象 Hashtable<String, Integer> hashtable = new Hashtable<>(); // 添加一些数据到哈希表中 hashtable.put("A", 1); hashtable.put("B", 2); hashtable.put("C", 3); // 使用containsValue()方法判断值是否存在于哈希表中 boolean result1 = hashtable.containsValue(2); // 返回true boolean result2 = hashtable.containsValue(4); // 返回false // 输出结果 System.out.println("值2是否存在于哈希表中:" + result1); System.out.println("值4是否存在于哈希表中:" + result2); } }
In the above code, we first create a Hashtable object, and then use the put() method to add three key-value pairs to the hash table. Next, we use the containsValue() method to determine whether value 2 and value 4 exist in the hash table, and finally output the results.
Run the above code, we will get the following output:
值2是否存在于哈希表中:true 值4是否存在于哈希表中:false
Since there is a key-value pair with a value of 2 in the hash table, containsValue(2) returns true; and the hash table There is no key-value pair with value 4, so containsValue(4) returns false.
Summary:
The above is the detailed content of Use the containsValue() method of the Hashtable class in Java to determine whether a value exists in the hash table. For more information, please follow other related articles on the PHP Chinese website!