The contains() method in Java checks whether the specified element or substring exists in the collection or string, and returns a Boolean value: Usage: boolean contains(Object element) Return value: The collection contains elements and returns true. Otherwise, return false. Note: Use equals() and indexOf() methods for comparison. The time complexity is O(n)
contains in Java Usage of ()
contains()
method in Java is used to check whether a collection (such as a list, array or string) contains a specific element or substring .
Usage:
contains()
The syntax of the method is as follows:
<code class="java">boolean contains(Object element)</code>
Among them:
element
is the element or substring you are looking for in the collection. Return value:
The method returns a Boolean value indicating whether the specified element or substring is contained in the collection:
true
. false
. Example:
List:
<code class="java">List<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); names.add("Bob"); System.out.println(names.contains("John")); // 输出:true System.out.println(names.contains("Alice")); // 输出:false</code>
Array:
<code class="java">int[] numbers = {1, 2, 3, 4, 5}; System.out.println(Arrays.asList(numbers).contains(3)); // 输出:true System.out.println(Arrays.asList(numbers).contains(6)); // 输出:false</code>
String:
<code class="java">String text = "Hello World"; System.out.println(text.contains("World")); // 输出:true System.out.println(text.contains("Java")); // 输出:false</code>
Notes:
contains()
method Use the equals()
method to compare elements. contains()
method uses the indexOf()
method to find substrings. contains()
The time complexity of the method is O(n), where n is the number of elements in the collection. 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!