In this guide, you will learn about the List contains() method in Java programming and how to use it with an example.
1. List contains() Method Overview
Definition:
The contains() method of the Java List interface is used to determine if a list contains a specified element.
Syntax:
list.contains(Object o)
Parameters:
Object o - the element whose presence in this list is to be tested.
Key Points:
- Returns true if the list contains the specified element, otherwise false.
- Uses the equals() method to check for equality, so custom objects should have an appropriate equals() implementation.
- The method will return false if the provided element is null and the list doesn't allow null elements.
2. List contains() Method Example
import java.util.ArrayList;
import java.util.List;
public class ListContainsExample {
public static void main(String[] args) {
// Create a new ArrayList with some elements
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits.contains("Banana")); // Outputs: true
System.out.println(fruits.contains("Grape")); // Outputs: false
// Working with custom objects
class Fruit {
private final String name;
public Fruit(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Fruit fruit = (Fruit) o;
return name.equals(fruit.name);
}
}
List<Fruit> fruitList = new ArrayList<>();
fruitList.add(new Fruit("Apple"));
System.out.println(fruitList.contains(new Fruit("Apple"))); // Outputs: true
}
}
Output:
true false true
Explanation:
In the provided example:
1. We initiated an ArrayList of strings with three fruit names.
2. We then used the contains() method to check if certain fruits were present in the list.
3. In the latter part of the example, we created a custom Fruit class with an equals() method. We showcased how contains() works effectively with custom objects when they have an appropriate equals() implementation.
The contains() method offers a simple way to verify the presence of an element in a list. Still, it's vital to remember its reliance on the equals() method for proper functionality.
Related Java List methods
Java List add() example
Java List clear() example
Java List contains() example
Java List get() example
Java List indexOf() example
Java List remove() example
Java List size() example
Java List toArray() example
Comments
Post a Comment
Leave Comment