Chapter 12. The Collection Interface

The interface Collection (see Figure 12-1) defines the core functionality that we expect of any collection other than a map. It provides methods in four groups.

Adding Elements

boolean add(E e)                           // add the element e
boolean addAll(Collection<? extends E> c)  // add the contents of c

The boolean result returned by these methods indicates whether the collection was changed by the call. It can be false for collections, such as sets, which will be unchanged if they are asked to add an element that is already present. But the method contracts specify that the elements being added must be present after execution so, if the collection refuses an element for any other reason (for example, some collections don’t permit null elements), these methods must throw an exception.

Collection
Figure 12-1. Collection

The signatures of these methods show that, as you might expect, you can add elements or element collections only of the parametric type.

Removing Elements

boolean remove(Object o)            // remove the element o
void clear()                        // remove all elements
boolean removeAll(Collection<?> c)  // remove the elements in c
boolean retainAll(Collection<?> c)  // remove the elements *not* in c

If the element 0 is null, remove removes a null from the collection if one is present. Otherwise, if an element e is present for which 0.equals(e), it removes it. If not, it leaves the collection unchanged. ...

Get Java Generics and Collections now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.