12.3 Modifying an ArrayList<E>
The ArrayList<E> class provides methods to append, insert, replace, and remove elements from a list. In addition, it has methods to modify the capacity of a list.
Adding Elements
The various add methods allow elements to be appended at the end of a list and also inserted at a specified index in the list.
boolean add(E element)
From
List<E>
interface
.
void add(int index, E element)
From
List<E>
interface
.
The first method will append the specified element to the end of the list. It returns true if the collection was modified as a result of the operation.
The second method inserts the specified element at the specified index. If necessary, it shifts the element previously at this index and any subsequent elements one position toward the end of the list. The method will throw an IndexOutOfBoundsException if the index is out of range (index < 0 || index > size()).
The type parameter E represents the element type of the list.
boolean addAll(Collection<? extends E> c)
From
List<E>
interface
.
boolean addAll(int index,
From
List<E>
interface
.
Collection<? extends E> c)
The first method inserts the elements from the specified collection at the end of the list. The second method inserts the elements from the specified collection at the specified index; that is, the method splices the elements of the specified collection into the list at the specified index. These methods return true if any elements were added. Elements are inserted using an iterator of the specified collection (§15.2, p. 791). The second method will throw an IndexOutOfBoundsException if the index is out of range (index < 0 || index > size()).
The declaration of the parameter c essentially means that parameter c can refer to any collection whose element type is E or whose element type is a subtype of E.
Leave a Reply