Get the Element from an ArrayList in Java

We can get the element from an ArrayList in Java using the get() method from the ArrayList class.

Syntax

public Object get(int index);


We need to provide the index of an element that we want to retrieve from the list.

Example

import java.util.*;

public class Test {

  public static void main(String[] args) {

    List<String> cities = new ArrayList<>(Arrays.asList("New York", "London", "Paris", "Chicago", "Rome"));

    // retrieve the second element from the list
    System.out.println(cities.get(2));

    // retrieve the 4th element from the list
    System.out.println(cities.get(4));
  }
}
Output: Paris Rome
 
Lists are zero-based indexes, which means that the first element has an index of 0The list we are using contains 5 elements, so valid indexes are from 0 to 4
 
If we provide an invalid index, the IndexOutOfBoundsException error will be thrown. See the following example:
import java.util.*;

public class Test {

  public static void main(String[] args) {

    List<String> cities = new ArrayList<>(Arrays.asList("New York", "London", "Paris", "Chicago", "Rome"));

    // retrieve the 5th element from the list
    System.out.println(cities.get(5));

  }
}
Output: Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 5 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.get(ArrayList.java:427) at com.alegrucoding.Test.main(Test.java:12)
 
That was all about how to get the element from an ArrayList in Java.

Happy coding!

Leave a Reply

Your email address will not be published.