Java Utility Library

Java ArrayList - get() Method



The java.util.ArrayList.get() method returns the element at specified index of the ArrayList.

Syntax

public E get(int index)

Here, E is the type of element maintained by the container.


Parameters

index Specify index number of the element in the ArrayList.

Return Value

Returns the element at specified index of the ArrayList.

Exception

Throws IndexOutOfBoundsException, if the index is out of range.

Example:

In the example below, the java.util.ArrayList.get() method returns element at specified index of the ArrayList.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);
    MyList.add(50);

    //printing ArrayList using get() method
    System.out.print("MyList contains:"); 
    for(int i = 0; i < MyList.size(); i++) {
      System.out.print(" " + MyList.get(i));
    }
  }
}

The output of the above code will be:

MyList contains: 10 20 30 40 50

❮ Java.util - ArrayList