Java 中 contains() 方法在集合或字符串中检查特定元素或子字符串是否存在,返回 true 表示包含,否则返回 false。它适用于各种比较和搜索操作,适用于 List、Set、Map 和 String 等类型。
Java 中 contains() 用法
在 Java 中,contains() 方法被用来检查一个集合或字符串中是否包含特定的元素或子字符串。它广泛用于各种比较和搜索操作。
语法
boolean contains(Object element)
参数
立即学习“Java免费学习笔记(深入)”;
返回值
用法示例
List
List<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); names.add("Bob"); if (names.contains("John")) { // John 已存在于列表中 }
Set
Set<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); if (numbers.contains(2)) { // 集合中包含数字 2 }
Map
Map<String, Integer> ages = new HashMap<>(); ages.put("John", 30); ages.put("Mary", 25); ages.put("Bob", 35); if (ages.containsKey("John")) { // John 已存在于映射中 }
String
String str = "Hello World"; if (str.contains("World")) { // 字符串中包含子字符串 "World" }
注意事项
以上就是java中contains用法的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号