O'Reilly logo

Java Generics and Collections by Philip Wadler, Maurice Naftalin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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<?> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required