top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Search an element of ArrayList with indexOf and lastIndexOf explain with example?

+1 vote
343 views
How to Search an element of ArrayList with indexOf and lastIndexOf explain with example?
posted Jan 21, 2016 by Joy Nelson

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();

    arrayList.add("2");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
    arrayList.add("1");
    arrayList.add("2");

    System.out.println(arrayList.contains("2"));

    int index = arrayList.indexOf("4");
    if (index == -1)
      System.out.println("not contain 4");
    else
      System.out.println("4 at index :" + index);

    int lastIndex = arrayList.lastIndexOf("1");
    if (lastIndex == -1)
      System.out.println("not contain 1");
    else
      System.out.println("Last index :"+ lastIndex);
  }
}

/*true
4 at index :3
Last index :5
*/
answer Jan 22, 2016 by Karthick.c
...