Java ArrayList get() Method

Java ArrayList Java ArrayList

The get() method retrieves an element from the dynamic array based on its index value.

The syntax of the get() method is:

arraylist.get(int index)

Note:arraylist is an object of the ArrayList class.

Parameter description:

  • index - The index value.

Return Value

Returns the element at the specified index in the dynamic array.

If the index value is out of range, an IndexOutOfBoundsException is thrown.

Example

Using the get() method in a String type 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);


        // Get the element at index 1
        String element = sites.get(1);
        System.out.println("The element at index 1 is: " + element);
    }
}

Executing the above program produces the following output:

网站列表: [Google, Example, Taobao]
索引值为 1 的元素为: Example

In the above example, we created an array named sites and used the get() method to retrieve the element at index 1.

Using the get() method with an Integer type dynamic array:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Create an array
        ArrayList<Integer> numbers = new ArrayList<>();

        // Insert elements into the array
        numbers.add(22);
        numbers.add(13);
        numbers.add(35);
        System.out.println("Numbers ArrayList: " + numbers);

        // Return the element at index 2
        int element = numbers.get(2);
        System.out.println("The element at index 2 is: " + element);
    }
}

Executing the above program produces the following output:

Numbers ArrayList: [22, 13, 35]
索引值为 2 的元素为: 35

In the above example, the get() method is used to access the element at index 2.

Note:We can also use the indexOf() method to return the index value of an element in the ArrayList. To learn more, please visitJava ArrayList indexOf()。

Java ArrayList Java ArrayList

Other Extensions