What is the usage of list contains in Java?

In Java, the List interface provides the contains(Object o) method to determine if a specified element is present in the list. This method returns a boolean value, returning true if the list contains the specified element and false otherwise.

Here is the example code:

List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");

if (list.contains("apple")) {
    System.out.println("List contains 'apple'");
} else {
    System.out.println("List does not contain 'apple'");
}

In the example above, we first created a List object containing three string elements, then used the contains method to check if the list contains the string “apple”. If it does, we output “List contains ‘apple’”, otherwise we output “List does not contain ‘apple’”.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds