Java ArrayList.indexOf() Method

 Posted On  | Yashwant Chavan 

In this tutorial you will learn about Java ArrayList.indexOf() method. It is used to get the index of the specified element in this list.

syntax

Returns the index of the first occurrence of the specified element in this list, It returns -1 if this list does not contain the element.

int java.util.ArrayList.indexOf(Object o)

Parameter

o - element to search for.

Return

int Returns the index of element.

Java ArrayList.indexOf() example

Refer below steps

  • Constructs an empty ArrayList with an initial capacity using new ArrayList<String>().
  • Add some elements in colors ArrayList using add() method.
  • Print List elements using for loop.
  • Get the index of Pink color (colors.indexOf("Pink")). It returns the index position as 3.
package com.technicalkeeda.app;

import java.util.ArrayList;

public class ArrayListIndexOf {
    public static void main(String[] args) {

        ArrayList <String> colors = new ArrayList <String> ();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        colors.add("Pink");
        colors.add("Black");
        colors.add("White");

        for (int i = 0; i < colors.size(); i++) {
            System.out.println("Index:- " + i + " Element:- " + colors.get(i));
        }

        System.out.println("\nindexOf Pink is :- " + colors.indexOf("Pink"));

    }
}

Output

Index:- 0 Element:- Red
Index:- 1 Element:- Green
Index:- 2 Element:- Blue
Index:- 3 Element:- Pink
Index:- 4 Element:- Black
Index:- 5 Element:- White

indexOf Pink is :- 3


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0327 seconds.