Java中的 SimpleBindings containsKey() 方法及示例
如果支持此 SimpleBindings 对象的此映射包含指定键的映射,则SimpleBindings 类的containsKey()方法用于返回 true。如果 SimpleBindings 对象包含此键,则该方法返回 true,否则返回 false。
句法:
public boolean containsKey(Object key)
参数:此方法仅接受一个参数键,该键是要在此映射中测试其存在的键。
返回值:如果此映射包含指定键的映射,则此方法返回 true。
异常:此方法抛出以下异常:
- NullPointerException : 如果键为空
- ClassCastException : 如果键不是字符串
- IllegalArgumentException : 如果键为空字符串
说明 containsKey() 方法工作的Java程序:
方案一:
// Java program to demonstrate containsKey() method
import javax.script.SimpleBindings;
public class GFG {
public static void main(String[] args)
{
// create simpleBindings object
SimpleBindings bindings = new SimpleBindings();
// add some keys with values
bindings.put("key1", "value1");
bindings.put("key2", "value2");
bindings.put("key3", "value3");
// check key2 is exists in bindings or not
boolean isKey2Exist = bindings.containsKey("key2");
// print
System.out.println("Key2 exits:" + isKey2Exist);
}
}
输出:
Key2 exits:true
方案二:
// Java program to demonstrate containsKey() method
import javax.script.SimpleBindings;
public class GFG {
public static void main(String[] args)
{
// create simpleBindings object
SimpleBindings asiaTeamList
= new SimpleBindings();
// add team in asiaTeamList
asiaTeamList.put("team1", "India");
asiaTeamList.put("team2", "Sri Lanka");
asiaTeamList.put("team3", "Pakistan");
asiaTeamList.put("team4", "Bangladesh");
// check England exists in bindings or not
boolean isKey2Exist
= asiaTeamList.containsKey("England");
// print
System.out.println("England exits in Asia Team:"
+ isKey2Exist);
}
}
输出:
England exits in Asia Team:false
参考资料: https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleBindings.html#containsKey(Java.lang.Object)