Chapter 17. The Collections Class
The class java.util.Collections
consists entirely of static methods that operate on or return collections. There are three main categories: generic
algorithms, methods that return empty or prepopulated
collections, and methods that create wrappers. We discuss these three categories in turn, followed
by a number of other methods which do not fit into a neat
classification.
All the methods of Collections
are
public and static, so for readability we will omit these modifiers from the
individual declarations.
Generic Algorithms
The generic algorithms fall into four major categories: changing element order in a list, changing the contents of a list, finding extreme values in a collection, and finding specific values in a list. They represent reusable
functionality, in that they can be applied to Lists
(or in some cases to Collections
) of any type. Generifying the types
of these methods has led to some fairly complicated declarations, so each
section discusses the declarations briefly after presenting
them.
Changing the Order of List Elements
There are seven methods for reordering lists in various ways. The
simplest of these is swap
, which
exchanges two elements and, in the case of a List
which implements RandomAccess
, executes in constant time. The
most complex is sort
, which transfers
the elements into an array, applies a merge sort to them in time
O(n log
n), and then returns them to the List
. All of the remaining methods execute in
time O(n).
void reverse(List<?> ...
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.