Java Reference
In-Depth Information
You create and sort the authors array in the same way as you did in the previous example. The elements
in the authors array are sorted into ascending sequence because you use the sort() method without
supplying a comparator, and the Comparable<> interface implementation in the Person class imposes
ascending sequence on objects.
You create the people array containing Person objects that might or might not be authors. You use the
binarySearch() method to check whether the elements from the people array appear in the authors
array in a loop:
for(Person person : people) {
index = Arrays.binarySearch(authors, person);
if(index >= 0) {
System.out.println(person + " was found at index position " +
} else {
System.out.println(person + " was not found. Return value is
" + index);
The person variable references each of the elements in turn. If the person object appears in the authors
array, the index is non-negative, and the first output statement in the if executes; otherwise, the second
output statement executes. You can see from the output that everything works as expected.
Array Contents as a String
The Arrays class defines several static overloads of the toString() method that return the contents of an
array you pass as the argument to the method as a String object. There are overloads of this method for
each of the primitive types and for type Object . The string that the methods return is the string representa-
tion of each of the array elements separated by commas, between square brackets. This is very useful when
you when to output an array in this way. For example:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Executing this code fragment produces the output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
For presenting a multidimensional array as a string, the Arrays class defines the static deepToString()
method that has a parameter of type Object[] . The method works for arrays of any number of dimensions
and array elements of any type, including primitive types. If the array elements are references, the string
representation of the element is produced by calling its toString() method.
Here's an example:
String[][] folks = {
{"Ann", "Arthur", "Arnie"},
{ "Bill", "Barbara", "Ben", "Brenda", "Brian"},
{"Charles", "Catherine"}};
Search WWH ::

Custom Search