Java Arraylist Contains
## Java ArrayList contains() Method
The `contains()` method in Java is a built-in function of the `ArrayList` class. It is used to determine whether a specific element exists within the dynamic array (ArrayList).
---
## Syntax and Usage
The syntax for the `contains()` method is as follows:
```java
boolean result = arraylist.contains(Object obj);
```
* **`arraylist`**: An instance of the `ArrayList` class.
* **`obj`**: The element whose presence in the list is to be tested.
### Parameters
* **`obj`**: The element to search for. This parameter is of type `Object`, meaning you can pass any object type that matches or is compatible with the elements stored in your `ArrayList`.
### Return Value
* Returns **`true`** if the specified element is present in the `ArrayList`.
* Returns **`false`** if the specified element is not found in the `ArrayList`.
---
## Code Examples
### Example 1: Using `contains()` with String Elements
The following example demonstrates how to use the `contains()` method with an `ArrayList` of `String` objects.
```java
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList sites = new ArrayList<>();
// Add elements to the ArrayList
sites.add("Google");
sites.add("YouTip");
sites.add("Taobao");
System.out.println("Website List: " + sites);
// Check if "YouTip" exists in the ArrayList
System.out.print("Does 'YouTip' exist in the arraylist? ");
System.out.println(sites.contains("YouTip"));
// Check if "Weibo" exists in the ArrayList
System.out.print("Does 'Weibo' exist in the arraylist? ");
System.out.println(sites.contains("Weibo"));
}
}
```
**Output:**
```text
Website List: [Google, YouTip, Taobao]
Does 'YouTip' exist in the arraylist? true
Does 'Weibo' exist in the arraylist? false
```
**Explanation:**
In this example, `sites.contains("YouTip")` returns `true` because `"YouTip"` is present in the list. Conversely, `sites.contains("Weibo")` returns `false` because `"Weibo"` is not in the list.
---
### Example 2: Using `contains()` with Integer Elements
The following example demonstrates how to use the `contains()` method with an `ArrayList` of `Integer` objects.
```java
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an ArrayList of Integers
ArrayList numbers = new ArrayList<>();
// Insert elements into the ArrayList
numbers.add(2);
numbers.add(3);
numbers.add(5);
System.out.println("Number ArrayList: " + numbers);
// Check if 3 exists in the ArrayList
System.out.print("Does 3 exist in the arraylist? ");
System.out.println(numbers.contains(3));
// Check if 1 exists in the ArrayList
System.out.print("Does 1 exist in the arraylist? ");
System.out.println(numbers.contains(1));
}
}
```
**Output:**
```text
Number ArrayList: [2, 3, 5]
Does 3 exist in the arraylist? true
Does 1 exist in the arraylist? false
```
---
## Important Considerations
### 1. How `contains()` Works Internally
Under the hood, the `contains()` method relies on the `equals()` method of the objects stored in the list. It iterates through the list and compares the target object with each element using:
```java
o == null ? get(i) == null : o.equals(get(i))
```
If a match is found where `equals()` returns `true`, then `contains()` returns `true`.
### 2. Custom Objects and `equals()`
If you are using `contains()` with an `ArrayList` of custom objects (e.g., a list of `User` or `Product` objects), you **must override the `equals()` method** (and ideally the `hashCode()` method) in your custom class. If you do not override `equals()`, the method will default to comparing object references (`==`), which may lead to unexpected `false` results even if two objects have identical field values.
### 3. Performance Complexity
The `contains()` method performs a linear search (scanning the list from the first element to the last). Therefore, its time complexity is **$O(n)$**, where $n$ is the number of elements in the `ArrayList`. If you need to perform frequent lookup operations on large datasets, consider using a collection with $O(1)$ lookup time, such as `HashSet`.
YouTip