ArrayList E get(int index) method in java

Let’s learn ArrayList E get(int index) method in java.

ArrayList E get(int index) method in java

get(int index) method of ArrayList class returns the element at the specified position in this list.

Syntax:

public Element get(int index)

Parameters:

index index of the element to return.

Throws:

IndexOutOfBoundsException – if the index is out of range(index < 0 || index >= size()).

Also read – ArrayList in java

Now let’s see example on ArrayList get(int index) method.

import java.util.ArrayList;
public class ArrayListGetExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("lion");
      al.add("tiger");
      al.add("deer");
      al.add("cheetah");
      al.add("elephant");
      al.add("fox");
      al.add("hyenas");
      al.add("jackal");
      System.out.println("Get second element of ArrayList: " + al.get(1));
      System.out.println("Get third element of ArrayList: " + al.get(2));
      System.out.println("Get fifth element of ArrayList: " + al.get(4));
      System.out.println("Get sixth element of ArrayList: " + al.get(5));
   }
}


Output:

Get second element of ArrayList: tiger
Get third element of ArrayList: deer
Get fifth element of ArrayList: elephant
Get sixth element of ArrayList: fox


Reference – oracle docs