The contains() method in Java checks whether a specific element or substring exists in a collection or string, and returns true to indicate inclusion, otherwise it returns false. It works with a variety of comparison and search operations on types such as List, Set, Map, and String.
contains() usage in Java
In Java, contains()
method Used to check whether a set or string contains a specific element or substring. It is widely used for various comparison and search operations.
Syntax
<code class="java">boolean contains(Object element)</code>
Parameters
element
- The element or child to search for StringReturn value
true
if the collection or string contains the element or substring ; Otherwise, return false
. Usage example
List
<code class="java">List<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); names.add("Bob"); if (names.contains("John")) { // John 已存在于列表中 }</code>
Set
<code class="java">Set<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); if (numbers.contains(2)) { // 集合中包含数字 2 }</code>
Map
<code class="java">Map<String, Integer> ages = new HashMap<>(); ages.put("John", 30); ages.put("Mary", 25); ages.put("Bob", 35); if (ages.containsKey("John")) { // John 已存在于映射中 }</code>
String
<code class="java">String str = "Hello World"; if (str.contains("World")) { // 字符串中包含子字符串 "World" }</code>
Notes
contains The ()
method iterates over the entire collection or string, so it may be less efficient, especially if the collection or string is large. equals()
method for comparison instead of contains()
. The contains()
method behaves differently with null
values depending on the collection type. For example, List
and Set
will treat null
as a valid element, but Map
will not. The above is the detailed content of How to use contains in java. For more information, please follow other related articles on the PHP Chinese website!