Java Reference
In-Depth Information
The ArrayList object contains fi ve Integer objects. The call to Collections.sort
includes a new Reverse object, which orders the numbers in reverse order. The output of
the previous statements is
30
12
7
7
-5
The natural ordering is ignored when a Comparator is supplied to the sort method.
Using a Comparator , you control the ordering of a list based on the needs of your business
logic.
Converting a List to an Array
The sort methods in Collections perform the list search in n log( n ) time, where n is the
number of elements in the list. To achieve this type of performance, the sort methods
actually convert the given List object to an array, sort the array, and then iterate over the
list, resetting each element from the corresponding position in the array.
For the exam, you do not need to understand how the sort method works behind the
scenes. However, the exam objectives specifi cally mention the ability to convert a list to
an array, which is achieved using the generic toArray method of the List interface:
<T> T[] toArray(T[] a)
The toArray method returns an array that contains all the elements of the list. This
generic version of toArray requires an array argument. The array passed in, if big
enough, is used to contain the list elements (and also returned). If the array passed in
is not big enough to hold the list, as in the following code, a new array is created and
returned:
List<String> list = new ArrayList<String>();
list.add(“one”);
list.add(“two”);
list.add(“three”);
String [] array = list.<String>toArray(new String [0]);
for(String s : array) {
System.out.print(s + “ “);
}
Search WWH ::




Custom Search