484 Part II: The Java Library
// Binary search for -9.
System.out.print("The value -9 is at location ");
int index =
Arrays.binarySearch(array, -9);
System.out.println(index);
}
static void display(int array[]) {
for(int i: array)
System.out.print(i + " ");
System.out.println();
}
}
The following is the output from this program:
Original contents: 0 -3 -6 -9 -12 -15 -18 -21 -24 -27
Sorted: -27 -24 -21 -18 -15 -12 -9 -6 -3 0
After fill(): -27 -24 -1 -1 -1 -1 -9 -6 -3 0
After sorting again: -27 -24 -9 -6 -3 -1 -1 -1 -1 0
The value -9 is at location 2
Why Generic Collections?
As mentioned at the start of this chapter, the entire Collections Framework was refitted for
generics when JDK 5 was released. Furthermore, the Collections Framework is arguably
the single mostimportant use of generics in the Java API. The reason for this is that generics
add type safety to the Collections Framework. Before moving on, it is worth taking some
time to examine in detail the significance of this improvement.
Let’s begin with an example that uses pre-generics code. The following program stores
a list of strings in anArrayListand then displays the contents of the list:
// Pre-generics example that uses a collection.
import java.util.*;
class OldStyle {
public static void main(String args[]) {
ArrayList list = new ArrayList();
// These lines store strings, but any type of object
// can be stored. In old-style code, there is no
// convenient way to restrict the type of objects stored
// in a collection
list.add("one");
list.add("two");
list.add("three");
list.add("four");
Iterator itr = list.iterator();
while(itr.hasNext()) {