AbstractList add(int index, E element) method in Java with Examples
The add(int index, E element) method of AbstractList is used to insert an element at the specified position in this list. The new element is inserted at the specified index in this list.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
public void add(int index, E element)
Parameters: This method takes 2 parameters :-
- index: index at which the specified element is to be inserted
- element: element to be inserted
Returns: The function returns a boolean value True if the element is successfully inserted in the List otherwise it returns False.
Exceptions:The exceptions present are :-
- ClassCastException: if the class of an element of this set is incompatible with the specified collection
- NullPointerException: if this set contains a null element and the specified collection does not permit null elements, or if the specified collection is null.
- UnsupportedOperationException: if the add operation is not supported by this list.
- IllegalArgumentException: if some property of the specified element prevents it from being added to this list.
- IndexOutOfBoundsException: if the index is out of range (index size()).
Below program illustrates the add(int index, int position) function of AbstractList class :
Before: [3, 6, 9, 12] After: [3, 4, 6, 9, 12]
Before: [Geeks, for, Computer, Portal] After: [Geeks, for, Geeks, Computer, Portal]