Name

Collections

Synopsis

This class defines static methods and constants that are useful for working with collections and maps. One of the most commonly used methods is sort( ), which sorts a List in place (the list cannot be immutable, of course). The sorting algorithm is stable, which means that equal elements retain the same relative order. One version of sort( ) uses a specified Comparator to perform the sort; the other relies on the natural ordering of the list elements and requires all the elements to implement java.lang.Comparable. reverseOrder( ) returns a Comparator object that reverses the order of another Comparator or that reverse the natural ordering of Comparable objects.

A related method is binarySearch( ). It efficiently (in logarithmic time) searches a sorted List for a specified object and returns the index at which a matching object is found. If no match is found, it returns a negative number. For a negative return value r, the value -(r+1) specifies the index at which the specified object can be inserted into the list to maintain the sorted order of the list. As with sort( ), binarySearch( ) can be passed a Comparator that defines the order of the sorted list. If no Comparator is specified, the list elements must all implement Comparable, and the list is assumed to be sorted according to the natural ordering defined by this interface.

See Arrays for methods that perform sorting and searching operations on arrays instead of collections.

The various methods whose ...

Get Java in a Nutshell, 5th Edition 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.