Home > Java > javaTutorial > body text

How to use contains in java

下次还敢
Release: 2024-05-08 05:07:07
Original
830 people have browsed it

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)

How to use contains in java

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>
Copy after login

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:

  • If the collection contains the element or substring, return true.
  • Otherwise, return 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>
Copy after login

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>
Copy after login

String:

<code class="java">String text = "Hello World";

System.out.println(text.contains("World")); // 输出:true
System.out.println(text.contains("Java")); // 输出:false</code>
Copy after login

Notes:

  • For collections, contains() method Use the equals() method to compare elements.
  • For strings, the 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template