Removing Element from the Specified Index in Java ArrayList
Last Updated :
31 Mar, 2023
The remove(int index) method present in java.util.ArrayList class removes the element at the specified position in this list and shifts any subsequent elements to the left (i.e. subtracts one from their indices).
Syntax :
public removed_element remove(int index)
Parameters: The index of the element to be removed.
Return Type: This method returns the element that was removed from the list.
Exception: This method throws IndexOutOfBoundsException if the index is out of range.
Java
import java.util.ArrayList;
public class GFG {
public static void main(String[] arg)
{
ArrayList<String> flower = new ArrayList<String>( 5 );
flower.add( "red-rose" );
flower.add( "tulip" );
flower.add( "sun-flower" );
flower.add( "marie-gold" );
flower.add( "orchid" );
System.out.println( "Size of list: "
+ flower.size());
System.out.println( "Flower ArrayList = " + flower);
System.out.println(
"Removing element at index = 2 " );
flower.remove( 2 );
System.out.println( "After removing element" );
System.out.println( "Size of list: "
+ flower.size());
System.out.println( "Flower ArrayList = " + flower);
}
}
|
Output
Size of list: 5
Flower ArrayList = [red-rose, tulip, sun-flower, marie-gold, orchid]
Removing element at index = 2
After removing element
Size of list: 4
Flower ArrayList = [red-rose, tulip, marie-gold, orchid]
Time Complexity: O(n)
Auxiliary Space: O(1)
As constant extra space is used.
When we will try to remove an element at the index which is greater than or equal to the size of the array list, the editor will give us the IndexOutOfBound Exception on running.
Java
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Integer> arrlist = new ArrayList<Integer>( 5 );
arrlist.add( 20 );
arrlist.add( 15 );
arrlist.add( 30 );
arrlist.add( 45 );
System.out.println( "Size of list: " + arrlist.size());
for (Integer number : arrlist) {
System.out.println( "Number = " + number);
}
arrlist.remove( 4 );
System.out.println( "Now, Size of list: " + arrlist.size());
for (Integer number : arrlist) {
System.out.println( "Number = " + number);
}
}
}
|
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 4
Time Complexity: O(n)
Auxiliary Space: O(1)
As constant extra space is used.
Share your thoughts in the comments
Please Login to comment...