In this example we will show how to search an element of ArrayList object with contains, indexOf and lastIndexOf methods in Java.
Source Code
package com.beginner.examples;
import java.util.ArrayList;
public class SearchArrayListElementExample {
public static void main(String[] args) {
ArrayList al = new ArrayList();
//
al.add("A");
al.add("B");
al.add("C");
al.add("D");
// The indexOf() method returns the indexOf this element,
// or -1 if it does not exist
int result = al.indexOf("C");
int result1 = al.indexOf("F");
System.out.println("Element C:" + result + "nElement F:" + result1);
}
}
Output:
Element C:2
Element F:-1
References
Imported packages in Java documentation: