Retrieve an element from ArrayList in Java


An element can be retrieved from the ArrayList in Java by using the java.util.ArrayList.get() method. This method has a single parameter i.e. the index of the element that is returned.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList = new ArrayList();
      aList.add("James");
      aList.add("George");
      aList.add("Bruce");
      aList.add("Susan");
      aList.add("Martha");
      System.out.println("The element at index 3 in the ArrayList is: " + aList.get(3));
   }
}

The output of the above program is as follows

The element at index 3 in the ArrayList is: Susan

Now let us understand the above program. The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList.

Then the ArrayList.get() method is used to retrieve the element at index 3 and this is displayed. A code snippet which demonstrates this is as follows

List aList = new ArrayList();
aList.add("James");
aList.add("George");
aList.add("Bruce");
aList.add("Susan");
aList.add("Martha");
System.out.println("The element at index 3 in the ArrayList is: " + aList.get(3));

Updated on: 13-Sep-2023

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements