Java中的Hashtable.contains()方法
Java中的java.util.Hashtable.contains(Object value)方法被用于检查一个特定的值是否被任何键所映射。
语法:
Hash_table.contains(Object value)
参数: 该方法接受一个对象类型的参数值,用于参照哈希表的值,确定其是否被映射。
返回值: 如果传递的值由哈希表中的任何键映射,则方法返回一个boolean值为true。
异常: 当传递的值为Null时,该方法会抛出NullPointerException。
下面的程序展示了上述方法的工作原理:
程序1:
// Java代码演示了contains()方法
import java.util.*;
public class Hash_Table_Demo {
public static void main(String[] args)
{
// 创建一个空的哈希表
Hashtable<Integer, String> hash_table =
new Hashtable<Integer, String>();
// 映射字符串值到整数键
hash_table.put(10, "Geeks");
hash_table.put(15, "4");
hash_table.put(20, "Geeks");
hash_table.put(25, "Welcomes");
hash_table.put(30, "You");
// 显示哈希表
System.out.println("Initial Table is: " + hash_table);
// 检查'Geeks'这个值是否存在
System.out.println("Is the value 'Geeks' present? " +
hash_table.contains("Geeks"));
// 检查'World'这个值是否存在
System.out.println("Is the value 'World' present? " +
hash_table.contains("World"));
}
}
初始表为:{10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
值 'Geeks' 是否存在? true
值 'World' 是否存在? false
程序2:
// Java代码演示了contains()方法
import java.util.*;
public class Hash_Table_Demo {
public static void main(String[] args)
{
// 创建一个空的哈希表
Hashtable<String, Integer> hash_table =
new Hashtable<String, Integer>();
// 映射整数值到字符串键
hash_table.put("Geeks", 10);
hash_table.put("4", 15);
hash_table.put("Geeks", 20);
hash_table.put("Welcomes", 25);
hash_table.put("You", 30);
// 显示哈希表
System.out.println("Initial Mappings are: " + hash_table);
// 检查值'10'是否存在
System.out.println("Is the value '10' present? " +
hash_table.containsValue(10));
// 检查值 '30'是否存在
System.out.println("Is the value '30' present? " +
hash_table.containsValue(30));
// 检查值 '40'是否存在
System.out.println("Is the value '40' present? " +
hash_table.containsValue(40));
}
}
初始映射为:{You=30, Welcomes=25, 4=15, Geeks=20}
值 '10'是否存在? false
值 '30' 是否存在? true
值 '40' 是否存在? false
极客教程