java中Contain和Containskey两个方法的区别及作用

tech2026-10-04  2

**### Contains()和ContainsKey()使用及区别

Contains()

用法:一个字符串中是否包含另外一个字符串

public static void main(String[] args) { String str1="abcdefg"; String str2="def"; boolean res = str1.contains(str2); if (res){ System.out.println("包括"); }else { System.out.println("不包含"); } }

注意:判断一个字符串是不是在领一个字符串中包含着,前提条件是你所判断的字符串再另一个字符串中是紧挨着的 例如: “abcdefgh”.contains(“def”) 该结果返回值为true, 如果“abcdefgh”.contains(“df”) 此时返回结果是false

ContainsKey()

用法:主要用于判断map中是否包含指定的键名

public static void main(String[] args) { Map<String,String> map=new HashMap<String,String>(); map.put("book","语文"); map.put("food","零食"); boolean res = map.containsKey("book"); boolean foods = map.containsValue("零食"); if(foods){ System.out.println("存在值"); }else { System.out.println("不存在值"); } if(res){ System.out.println(map.get("book")); System.out.println("存在键"); }else { System.out.println("不存在键"); } } ```**
最新回复(0)