java arraylist get index code example

Example 1: ArrayList E get(int index) method in java

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));
   }
}

Example 2: ArrayList indexOf(Object o) method in java

import java.util.ArrayList;
public class ArrayListIndexOfMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>(5);
      al.add(8);
      al.add(6);
      al.add(5);
      al.add(7);
      al.add(9);
      System.out.print("ArrayList values are: ");
      for(Integer num : al)
      {
         System.out.print(num);
         System.out.print(" ");
      }
      // indexOf() method to find index of 5
      int position = al.indexOf(5);
      System.out.println("\nElement 5 is at index: " + position);
   }
}

Example 3: java arraylist access index

List<String> cities = new ArrayList<String>();
cities.add("Tuguegarao City");
cities.add("Tabuk City");
cities.add("Davao City");

System.out.println(cities.get(1)); //prints "Tabuk City"

Example 4: arraylist get value at index java

get(index);

Example 5: java first index of an arraylist

ArrayList<Type> array = new ArrayList<Type>();
System.out.printLn(array[0]);