ArrayList.remove(int): This method is available in java.util.ArrayList class of Java.
Syntax:
E java.util.ArrayList.remove(int index)
This method takes one argument of type int as its parameter. This method removes the element at the specified position in this list.
Parameters: One parameter is required for this method.
index: the index of the element to be removed.
Returns: the element that was removed from the list.
Throws:
IndexOutOfBoundsException - if the index is out of range(index < 0 || index >= size())
Approach 1: When no exception
Java
import java.util.ArrayList;public class ArrayListRemove {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(2);arr.add(4);System.out.println("Size before remove " + arr.size());arr.remove(0);System.out.println("Size after remove " + arr.size());}}
Output:
Size before remove 3
Size after remove 2
Approach 2: IndexOutOfBoundsException
Java
import java.util.ArrayList;public class ArrayListRemove {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(2);arr.add(4);System.out.println("Size before remove " + arr.size());arr.remove(4);System.out.println("Size after remove " + arr.size());}}
Output:
Size before remove 3 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 3 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.remove(ArrayList.java:504)
No comments:
Post a Comment