How can I get elements from a Java List?



Elements can be retrieved from a list using get() method.

Syntax

E get(int index)

Returns the element at the specified position in this list.

Parameters

  • index − Index of the element to return.

Returns

The element at the specified position in this list.

Throws

  • IndexOutOfBoundsException − If the index is out of range (index < 0 || index >= size()).

Here index represents the index of the element E in the list. It throws IndexOutOfBoundsException if index is out of range.

Example

Following is the example getting elements from a list using get() method −

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<String> list = new ArrayList<>();
      list.add("A");
      list.add("B");
      list.add("C");
      System.out.println("List: " + list);
      System.out.println("List(1): " + list.get(1));
      try {
         System.out.println("List(3): " + list.get(3));
      }catch(IndexOutOfBoundsException e) {
         System.out.println(e);
      }
   }
}

Output

This will produce the following result −

List: [A, B, C]
List(1): B
java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

Advertisements