Java Reference
In-Depth Information
Arrays
.
sort
(
haystack
);
// Look for needle in haystack
i
=
Arrays
.
binarySearch
(
haystack
,
NEEDLE
);
iif
(
i
>=
0
) {
// Found it, we win.
System
.
out
.
println
(
"Value "
+
NEEDLE
+
" occurs at haystack["
+
i
+
"]"
);
return
return true
true
;
}
else
else
{
// Not found, we lose.
System
.
out
.
println
(
"Value "
+
NEEDLE
+
" does not occur in haystack; nearest value is "
+
haystack
[-(
i
+
2
)] +
" (found at "
+ -(
i
+
2
) +
")"
);
return
return false
false
;
}
}
}
The
Collections.binarySearch()
works almost exactly the same way, except it looks in a
Collection
, which must be sorted (presumably using
Collections.sort
, as discussed in
Converting a Collection to an Array
Problem
You have a
Collection
but you need a Java language array.
Solution
Use the
Collection
method
toArray()
.
Discussion
If you have an
ArrayList
or other
Collection
and you need an array, you can get it just by
calling the
Collection
's
toArray()
method. With no arguments, you get an array whose
type is
Object[]
. You can optionally provide an array argument, which is used for two pur-
poses: