java.util.Collections
class contains static utility methods for manipulating collections. Some useful Collections methods
Assume the following declarations have been made, whereT
is a class or interface type. int i;
ListlistC; // List of the Comparable objects.
Listlist; // Any kind of list. Need not be Comparable.
Comparatorcomp;
T key;
T t;
Collectioncoll; // Any kind of Collection (List, Set, Deque).
CollectioncollC; // Any kind of Collection implementing Comparable.
Rearranging - Sorting, Shuffling, . . . | ||
Collections.sort(listC) | Sorts listC . Elements must be Comparable | |
Collections.sort(list, comp) | Sorts list using a comparator. | |
Collections.shuffle(list) | Puts the elements of list in random order. | |
Collections.reverse(list) | Reverses the elements of list . | |
Searching | ||
i = | Collections.binarySearch(listC, key) | Searches list for key . Returns index of element or negative value if not found. See Binary Search. |
i = | Collections.binarySearch(list, key, comp) | Searches in list for key using Comparator comp. |
t = | Collections.max(collC) | Returns maximum valued Comparable object in collC . |
t = | Collections.max(coll, comp) | Maximum valued object in coll using Comparator comp . |
t = | Collections.min(collC) | Returns minimum valued Comparable object in collC . |
t = | Collections.min(coll, comp) | Minimum valued object in coll using Comparator comp . |
Searching may also be implemented in data structure classes
All List and Set classes implement thecontains()
method, which performes a linear search on lists (O(N)), a binary search for TreeSets (O(log N)), and a hashed search for HashSets (O(1)). Maps define
get()
to search for the key. For HashMaps the search is O(1), and for TreeMaps the search is O(log N).
No comments:
Post a Comment