get elements arraylist java code example

Example 1: 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 2: how to select a element in an arraylist java

import java.util.ArrayList;
import java.util.Arrays;
 
public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles", "dough"));
         
        String firstName = list.get(0);         //alex
        String secondName = list.get(1);        //brian
         
        System.out.println(firstName);
        System.out.println(secondName);
    }
}

Tags:

Java Example