boolean containsKey(Object key) 方法:判断集合中是否完全包含与key相同的键。
例如下面的例子:
给定一个整数数组 nums 和一个整数目标值 target,在该数组中找出 和为目标值 的那 两个 整数,并输出它们的数组下标。
int[] n={1,8,7,4,6,2};
Integer sum=10;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for(int i=0;i<n.length;i++){
if(hashMap.containsKey(sum-n[i])){
System.out.println(hashMap.get(sum-n[i])+"----"+i);
}
hashMap.put(n[i],i);
}
通过containsKey判断,输出下标。
本例用containsKey保证了时间复杂度O(n)相对较低,采用for双循环的话,时间复杂度为O(n^n)。但是空间复杂度会提高。O(n)>O(1)
boolean containsValue(Object value) 方法:判断集合中是否有一个或者多个与value相同的值。
Map<String,String> map = new HashMap<String, String>();
//添加数据
map.put("1001", "张三");
map.put("1002", "李四");
map.put("1003", "李四");
//输出结果
System.out.println("该Map集合中是否包含学生 李四 :"+(map.containsValue("李四")?"包含":"不包含"));
System.out.println("该Map集合中是否包含学生 王五:"+(map.containsValue("王五")?"包含":"不包含"));
console:
该Map集合中是否包含学生 李四 :包含
该Map集合中是否包含学生 王五:不包含