English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java ArrayList get() Usage and Example

Java ArrayList Methods

The Java ArrayList get() method returns the element existing at the specified position.

The syntax of the get() method is:

arraylist.get(int index)

get() parameter

  • index - Position of the element to be accessed

get() return value

  • Returns the element existing at the specified position.

Note: If the index is out of range, the get() method will throw an exception exception IndexOutOfBoundsException.

Example1: get() method with string ArrayList

import java.util.ArrayList;
class Main {
    public static void main(String[] args) {
        //Create ArrayList
        ArrayList<String> languages = new ArrayList<>();
        //Insert Element into ArrayList
        languages.add("JavaScript");
        languages.add("Java");
        languages.add("Python");
        System.out.println("Programming languages: " + languages);
        //Access index1element at the location
        String element = languages.get(1);
        System.out.println("Index1: element: " + element);
    }
}

Output Result

Programming languages: [JavaScript, Java, Python]
Index1: Java

In the above example, we created an array list named languages. Here, the get() method is used to access the element at the index1elements exist at the location.

Example2: get() method with integer ArrayList

import java.util.ArrayList;
class Main {
    public static void main(String[] args) {
        //Create ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        // Insert Element into ArrayList
        numbers.add(22);
        numbers.add(13);
        numbers.add(35);
        System.out.println("Number ArrayList: " + numbers);
        //Return Position2element
        int element = numbers.get(2);
        System.out.println("Index2element: " + element);
    }
}

Output Result

Number ArrayList: [22, 13, 35]
Index2: element: 35

Here, the get() method is used to access the element at the index2element at the location.

NoteWe can also use the indexOf() method to obtain the index value of the element (number). For more information, please visitJava ArrayList indexOf().

Java ArrayList Methods