Easy Tutorial
❮ Java Hashmap Put Java Arraylist Addall ❯

Java ArrayList get() Method

Java ArrayList

The get() method retrieves an element from the dynamic array by its index.

The syntax for the get() method is:

arraylist.get(int index)

Note: arraylist is an object of the ArrayList class.

Parameter:

Return Value

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

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

Example

Using the get() method with an array of String type:

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("tutorialpro");
        sites.add("Taobao");
        System.out.println("Website List: " + sites);

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

Executing the above program outputs:

Website List: [Google, tutorialpro, Taobao]
Element at index 1: tutorialpro

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 a dynamic array of Integer type:

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("Element at index 2: " + element);
    }
}

Executing the above program outputs:

Numbers ArrayList: [22, 13, 35]
Element at index 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 of an element in the ArrayList. For more information, visit Java ArrayList indexOf().

Java ArrayList

❮ Java Hashmap Put Java Arraylist Addall ❯