Java Reference
In-Depth Information
The algorithm is similar to optimally looking for a name in a phone book. Start by
openingthebooktotheexactmiddle.Ifthenameisnotonthatpage,proceedtoopen
thebooktotheexactmiddleofthefirsthalforthesecondhalf,dependingoninwhich
half the name occurs. Repeat until you find the name (or not).
Applying a linear search to 4,000,000,000 elements results in approximately
2,000,000,000comparisons(onaverage),whichtakestime.Incontrast,applyingabin-
arysearchto4,000,000,000elementsresultsinamaximumof32comparisons.Thisis
why
Arrays
contains
binarySearch()
methodsandnotalso
linearSearch()
methods.
Followingisasamplingofthe
Collections
class'scollection-orientedclassmeth-
ods:
•
static <T extends Object&Comparable<? super T>> T
min(Collection<? extends T> c)
returns the minimum element
ofcollection
c
according tothe natural ordering ofits elements. Forexample,
System.out.println(Collections.min(Arrays.asList(10,
3, 18, 25)));
outputs
3
. All of
c
's elements must implement the
Com-
parable
interface. Furthermore, all elements must be mutually comparable.
This method throws
NoSuchElementException
when
c
is empty.
•
static void reverse(List<?> l)
reverses the order of list
l
's
elements. For example,
List<String> birds = Ar-
rays.asList("Robin", "Oriole", "Bluejay"); Collec-
tions.reverse(birds); System.out.println(birds);
results
in
[Bluejay, Oriole, Robin]
as the output.
•
static <T> List<T> singletonList(T o)
returns an immutable
list containing only object
o
. For example,
list.removeAll(Collections.singletonList(null));
re-
moves all
null
elements from
list
.
•
static <T> Set<T> synchronizedSet(Set<T> s)
returns a
synchronized (thread-safe) set backed by set
s
; for example,
Set<String>
ss = Collections.synchronizedSet(new
HashSet<String>());
. In order to guarantee serial access, it is critical
that all access to the backing set is accomplished through the returned set.
•
static <K,V> Map<K,V> unmodifiableMap(Map<? extends
K,? extends V> m)
returnsanunmodifiableviewofmap
m
;forexample,
Map<String,
Integer>
msi
=
Collec-