Replacing Elements – Collections, Part I: ArrayList

Replacing Elements

The following methods replace elements in a list with new elements.

Click here to view code image

E set(int index, E element)                         
From
 List<E>
interface
.

Replaces the element at the specified index with the specified element. It returns the previous element at the specified index. The method throws an IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).

Click here to view code image

default void replaceAll(UnaryOperator<E> operator)  
From
 List<E>
interface
.

Replaces each element of this list with the result of applying the unary operator (§13.10, p. 720) to that element. See also the List<E> interface (§15.3, p. 801).

Removing Elements

A summary of selected methods that can remove elements of a list is given here:

Click here to view code image

void clear()                                         
From
 List<E>
interface
.

Deletes all elements from the list. The list is empty after the call, so it has size 0.

Click here to view code image

E remove(int index)                                 
From
 List<E>
interface
.
boolean remove(Object element)                      
From
 List<E>
interface
.

The first method deletes and returns the element at the specified index. The method throws an IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).

The second method removes the first occurrence of the element from the list, using object value equality. The method returns true if the call was successful. This method does not throw an exception if an element value is null, or if it is passed a null value.

Both methods will contract the list accordingly if any elements are removed.

Click here to view code image

boolean removeAll(Collection<?> c)                  
From
 List<E>
interface
.
boolean removeIf(Predicate<? super E> filter) 
From
 Collection<E>
interface
.

The first method removes from this list all elements that are contained in the specified collection.

The second method removes from this list all elements that satisfy the filtering criteria defined by a lambda expression that implements the Predicate<T> functional interface (§13.6, p. 703). See also filtering a list (§15.2, p. 797).

Both methods return true if the call was successful. The list is contracted accordingly if any elements are removed.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *