Java ArrayList indexOf() Method

Java ArrayList Java ArrayList

The indexOf() method returns the index value of an element in the dynamic array.

The syntax of the indexOf() method is:

arraylist.indexOf(Object obj)

Note:arraylist is an object of the ArrayList class.

Parameter details:

  • obj - the element to search for

Return Value

Returns the index value of the position of the specified element in the dynamic array.

If the obj element appears multiple times in the dynamic array, the index value of the first occurrence of obj in the array is returned.

If the specified element does not exist in the dynamic array, the indexOf() method returns -1.

Example

Get the index of an element in the dynamic array:

Example

import java.util.ArrayList;

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

        // create an array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        System.out.println("Website list: " + sites);


        // find the element whose position index is Example
        int position1 = sites.indexOf("Example");
        System.out.println("Index position of Example: " + position1);

        // find the element whose position index is Weibo
        int position2 = sites.indexOf("Weibo");
        System.out.println("Index position of Weibo: " + position2);
    }
}

The output of the above program is:

Example 的索引位置: 1
Weibo 的索引位置: -1

In the above example, we created a dynamic array named sites.

Note these expressions:

// 元素存在于动态数组中,返回 1
sites.indexOf("Example");

//元素存在动态数组中不存在,返回 -1
sites.indexOf("Weibo");

Get the position of the first occurrence of an element:

Example

import java.util.ArrayList;

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

        // create an array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("Example");
        sites.add("Taobao");
        sites.add("Example");
        System.out.println("Website list: " + sites);


        // find the element whose position index is Example
        int position1 = sites.indexOf("Example");
        System.out.println("Index position of Example: " + position1);
    }
}

The output of the above program is:

网站列表: [Google, Example, Taobao, Example]
Example 的索引位置: 1

In the above example, we created a dynamic array named sites. Here we used the indexOf() method to get the position of the Example element.

Example appears at two different positions in the array list. In this case, the method returns the index of the first occurrence of Example (i.e., 1).

If we want to get the position of the last occurrence of Example, we can use the lastIndexOf() method. To learn more, please visitJava ArrayList lastIndexOf()。

Note:We can also use theJava ArrayList get()method to get the element at a specified index.

Java ArrayList Java ArrayList

Other Extensions