ArrayList.add(int, E): This method is available in java.util.ArrayList class of Java.
Syntax:
void java.util.ArrayList.add(int index, E element)
This method takes two arguments. This method inserts the specified element at the specified position in this list.
Parameters: Two parameters are required for this method.
index: index at which the specified element is to be inserted.
element: the element to be inserted.
Throws:
1. IndexOutOfBoundsException - if the index is out of range(index < 0 || index > size())
Approach 1: When no exceptions
Java
import java.util.ArrayList;public class ArrayListAddAtIndex {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(100);arr.add(234);arr.add(0, 2);arr.forEach((n -> System.out.print(n + " ")));}}
Output:
2 1 100 234
Approach 2: IndexOutOfBoundsException
Java
import java.util.ArrayList;public class ArrayListAddAtIndex {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();arr.add(1);arr.add(100);arr.add(234);arr.add(4, 2);arr.forEach((n -> System.out.print(n + " ")));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756) at java.base/java.util.ArrayList.add(ArrayList.java:481)
No comments:
Post a Comment