Given an ArrayList collection in Java, the task is to remove the first element from the ArrayList.
Example:
Input: ArrayList[] = [10, 20, 30, 1, 2]
Output: [20, 30, 1, 2]
After removing the first element 10, the ArrayList is:
[20, 30, 1, 2]
Input: ArrayList[] = [1, 1, 2, 2, 3]
Output: [1, 2, 2, 3]
After removing the first element 1, the ArrayList is:
[1, 2, 2, 3]
We can use the remove() method of ArrayList container in Java to remove the first element.
ArrayList provides two overloaded remove() method:
Below is the implementation to delete the first element using the two approaches:
- Program 1: Using remove(int index). Index of elements in an ArrayList starts from zero. Therefore, index of first element in an ArrayList is 0.
import java.util.List;
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<>();
al.add( 10 );
al.add( 20 );
al.add( 30 );
al.add( 1 );
al.add( 2 );
int index = 0 ;
al.remove(index);
System.out.println( "Modified ArrayList : " + al);
}
}
|
Output:
Modified ArrayList : [20, 30, 1, 2]
- Program 2: Using remove(Object obj).
import java.util.List;
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<>();
al.add( 10 );
al.add( 20 );
al.add( 30 );
al.add( 1 );
al.add( 2 );
al.remove( new Integer( 10 ));
System.out.println( "Modified ArrayList : " + al);
}
}
|
Output:
Modified ArrayList : [20, 30, 1, 2]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Jan, 2020
Like Article
Save Article