Java Reference
In-Depth Information
40
System.out.print( "The list is: " );
41
42
for (Character element : listRef)
43
System.out.printf( "%s " , element);
44
45
Collections.max(listRef)
Collections.min(listRef)
System.out.printf( "%nMax: %s" ,
);
46
System.out.printf( " Min: %s%n" ,
);
47
}
48
} // end class Algorithms1
list contains:
The list is: P C M
Max: P Min: C
After calling reverse, list contains:
The list is: M C P
Max: P Min: C
After copying, copyList contains:
The list is: M C P
Max: P Min: C
After calling fill, list contains:
The list is: R R R
Max: R Min: R
Fig. 16.11 | Collections methods reverse , fill , copy , max and min . (Part 2 of 2.)
Line 13 creates List<Character> variable list and initializes it with a List view of
the Character array letters . Lines 14-15 output the current contents of the List . Line
18 calls Collections method reverse to reverse the order of list . Method reverse takes
one List argument. Since list is a List view of array letters , the array's elements are
now in reverse order. The reversed contents are output in lines 19-20. Line 27 uses Col-
lections method copy to copy list 's elements into copyList . Changes to copyList do
not change letters , because copyList is a separate List that's not a List view of the array
letters . Method copy requires two List arguments—the destination List and the
source List . Line 32 calls Collections method fill to place the character 'R' in each
list element. Because list is a List view of the array letters , this operation changes
each element in letters to 'R' . Method fill requires a List for the first argument and
an Object for the second argument—in this case, the Object is the boxed version of the
character 'R' . Lines 45-46 call Collections methods max and min to find the largest and
the smallest element of a Collection , respectively. Recall that interface List extends
interface Collection , so a List is a Collection .
16.7.4 Method binarySearch
The high-speed binary search algorithm—which we discuss in detail in Section 19.4—is
built into the Java collections framework as a static Collections method binarySearch .
This method locates an object in a List (e.g., a LinkedList or an ArrayList ). If the object
is found, its index is returned. If the object is not found, binarySearch returns a negative
 
 
Search WWH ::




Custom Search