Interface List
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.
The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.
The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.
The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.
The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.
Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.
Unmodifiable Lists
- They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
- They disallow null elements. Attempts to create them with null elements result in NullPointerException .
- They are serializable if all elements are serializable.
- The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
- The lists and their subList views implement the RandomAccess interface.
- They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
- They are serialized as specified on the Serialized Form page.
This interface is a member of the Java Collections Framework.
Remove Element from an ArrayList in Java
Learn to remove an item from an ArrayList using the remove() and removeIf() methods. The remove() method removes either the specified element or an element from the specified index. The removeIf() removes all elements matching a Predicate.
The ArrayList.remove() method is overloaded.
E remove(int index) boolean remove(E element))
- The remove(int index) – removes the element at the specified index and returns the removed item.
- remove(E element) – remove the specified element by value and returns true if the element was removed, else returns false.
The removeAll() accepts a collection and removes all elements of the specified collection from the current list.
boolean removeAll(Collection c)
The removeIf() accepts a Predicate to match the elements to remove.
boolean removeIf(Predicate filter)
2. Remove an Element by Specified Index
The remove(index) method removes the specified element E at the specified position in this list. It removes the element currently at that position, and all subsequent elements are moved to the left (will subtract one from their indices).
Note that List Indices start with 0.
ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles") ); System.out.println(namesList); //list size is 3 //Remove element at 1 index namesList.remove(1); System.out.println(namesList); //list size is 2
[alex, brian, charles] [alex, charles]
2. Remove Specified Element(s) By Value
The remove(Object) method removes the first occurrence of the specified element E in this list. As this method removes the object, the list size decreases by one.
ArrayList namesList = new ArrayList<>(Arrays.asList( "alex", "brian", "charles", "alex") ); System.out.println(namesList); namesList.remove("alex"); System.out.println(namesList);
[alex, brian, charles, alex] [brian, charles, alex]
To remove all occurrences of the specified element, we can use the removeAll() method. As this method accepts a collection argument, we first need to wrap the element to remove inside a List.
namesList.removeAll(List.of("alex"));
3. Remove Element(s) with Matching Condition
We can use another super easy syntax from Java 8 stream to remove all elements for a given element value using the removeIf() method.
The following Java program uses List.removeIf() to remove multiple elements from the arraylist in java by element value.
ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles", "alex") ); System.out.println(namesList); namesList.removeIf( name -> name.equals("alex")); System.out.println(namesList);
[alex, brian, charles, alex] [brian, charles]
Java ArrayList.removeAll() – Remove All Occurrences of an Element
ArrayList removeAll() removes all of matching elements that are contained in the specified method argument collection. It removes all occurrences of matching elements, not only first occurrence.
1. ArrayList removeAll() method
Internally, the removeAll() method iterate over all elements of arraylist. For each element, it pass element to contains() method of argument collection.
If element is found in argument collection, it re-arranges the index. If element is not found, it retains the element inside backing array.
public boolean removeAll(Collection c) < Objects.requireNonNull(c); return batchRemove(c, false); >private boolean batchRemove(Collection c, boolean complement) < final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try < for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; >finally < // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) < System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; >if (w != size) < // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; >> return modified; >
Method parameter – collection containing elements to be removed from this list.
Method returns – true if this list changed as a result of the call.
Method throws – ClassCastException – if the class of an element of this list is incompatible with the specified collection. It may also throw NullPointerException if this list contains a null element and the specified collection does not permit null elements.
2. ArrayList removeAll() example
Java program to remove all occurrences of an object from the arraylist using removeAll() method.
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class ArrayListExample < public static void main(String[] args) throws CloneNotSupportedException < ArrayListalphabets = new ArrayList<>(Arrays.asList("A", "B", "A", "D", "A")); System.out.println(alphabets); alphabets.removeAll(Collections.singleton("A")); System.out.println(alphabets); > >
That’s all for the ArrayList removeAll() method in Java.