Prerequisite: ArrayList in Java Given an ArrayList, the task is to get the first and last element of the ArrayList in Java, Examples:
Input: ArrayList = [1, 2, 3, 4] Output: First = 1, Last = 4 Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] Output: First = 12, Last = 89
Approach:
- Get the ArrayList with elements.
- Get the first element of ArrayList with use of get(index) method by passing index = 0.
- Get the last element of ArrayList with use of get(index) method by passing index = size – 1.
Below is the implementation of the above approach:Â
Java
// Java code to find first and last element // of ArrayList Â
import java.util.ArrayList; Â
public class GFG { Â
    // main method     public static void main(String[] args)     { Â
        // creating an Empty Integer ArrayList         ArrayList<Integer> list = new ArrayList<Integer>( 5 ); Â
        // using add() to initialize values         list.add( 1 );         list.add( 2 );         list.add( 3 );         list.add( 4 ); Â
        // printing initial value ArrayList         System.out.print("ArrayList: " + list); Â
        // find first element         int first = list.get( 0 ); Â
        // find last element         int last = list.get(list.size() - 1 ); Â
        // print first and last element of ArrayList         System.out.println("\nFirst : " + first                            + ", Last : " + last);     } } |
ArrayList: [1, 2, 3, 4] First : 1, Last : 4
Time Complexity: O(1)
Auxiliary Space: O(1)