Java AbstractSequentialList | add()
AbstractSequentialList uses the add() method specified by the List interface and overridden in class AbstractList. Hence AbstractSequentialList do not have a add() method of its own. Instead it has add(int index, E element) method.
AbstractSequentialList add(int index, E element) method inserts the specified element at the specified position in this list. It shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). This implementation first gets a list iterator pointing to the indexed element (with listIterator(index)). Then, it inserts the specified element with ListIterator.add.
Therefore, add(E element) and add(int index, E element) both can be used with AbstractSequentialList class.
public void add(int index, E element)
Parameters: This method takes two parameters:
- index – It represents the index, of type Integer, at which the specified element is to be inserted. This parameter is optional. If not specified, then the specified element is inserted at the last position in the list.
- element – It represents the element, of type E, to be inserted into the list.
Exceptions: This method throws following exceptions:
- UnsupportedOperationException – if the add operation is not supported by this list
- ClassCastException – if the class of the specified element prevents it from being added to this list
- NullPointerException – if the specified element is null and this list does not permit null elements
- 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 are the programs to illustrate add() method:
Program 1: Adding the elements, by without passing the index
[5, 6, 7]
Java-CollectionsRemove term: Java-Functions Java-Functions
Program 2: Adding the elements, by passing the index
[8, 9, 7, 10]
Program 3: To demonstrate IndexOutOfBoundException
[5, 9, 6, 7, 10, 8, 7] Exception: java.lang.IndexOutOfBoundsException: Index: 10, Size: 7
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.