Chapter 16. 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’ll discuss each of these in turn, then consider a number of other methods that 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.
The choice of algorithm used by the methods that act on Lists often depends on whether the List being processed implements the marker interface RandomAccess. Classes implement this interface to indicate to generic methods that a long list of that class is more efficiently processed using get than by using an iterator. ArrayList implements RandomAccess; LinkedList does not.
Changing the Order of List Elements
void reverse(List<?> list) |
reverse the ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access