Retrieve an element from ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

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));
raja
Published on 17-Jan-2019 14:53:22
Advertisements