AhmadLang / Java, How To Program, 2004
.pdf
Line 24 calls Collections method reverse to reverse the order of list. Method reverse takes one List argument. In this case, list is a List view of array letters. Array letters now has its elements in reverse order. Line 28 copies the elements of list into copyList, using Collections method copy. Changes to copyList do not change letters, because copyList is a separate List that is not a List view for letters. Method copy requires two List arguments. Line 32 calls Collections method fill to place the string "R" in each element of list. Because list is a List view of 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. Lines 4546 call Collections methods max and min to find the largest and the smallest element of the collection, respectively. Recall that a List is a Collection, so lines 4546 can pass a List to methods max and min.
[Page 932]
19.6.4. Algorithm binarySearch
In Section 16.2.2, we studied the high-speed binary-search algorithm. This algorithm is built into the Java collections framework as a static method of class Collections. The binarySearch algorithm locates an object in a List (i.e., a LinkedList, a Vector or an ArrayList). If the object is found, its index is returned. If the object is not found, binarySearch returns a negative value. Algorithm binarySearch determines this negative value by first calculating the insertion point and making its sign negative. Then, binarySearch subtracts 1 from the insertion point to obtain the return value, which guarantees that method binarySearch returns positive numbers (>=0) if and only if the object is found. If multiple elements in the list match the search key, there is no guarantee which one will be located first. Figure 19.14 uses the binarySearch algorithm to search for a series of strings in an ArrayList.
Figure 19.14. Collections method binarySearch.
(This item is displayed on pages 932 - 933 in the print version)
1// Fig. 19.14: BinarySearchTest.java
2// Using algorithm binarySearch.
3import java.util.List;
4import java.util.Arrays;
5import java.util.Collections;
6import java.util.ArrayList;
7
8public class BinarySearchTest
9{
10private static final String colors[] = { "red", "white",
11"blue", "black", "yellow", "purple", "tan", "pink" };
12private List< String > list; // ArrayList reference
13
14// create, sort and output list
15public BinarySearchTest()
16{
17list = new ArrayList< String >( Arrays.asList( colors ) );
18Collections.sort( list ); // sort the ArrayList
19System.out.printf( "Sorted ArrayList: %s\n", list );
20} // end BinarySearchTest constructor
21
22// search list for various values
23private void search()
24{
25printSearchResults( colors[ 3 ] ); // first item
26printSearchResults( colors[ 0 ] ); // middle item
27printSearchResults( colors[ 7 ] ); // last item
28printSearchResults( "aqua" ); // below lowest
29printSearchResults( "gray" ); // does not exist
30printSearchResults( "teal" ); // does not exist
31} // end method search
32
33// perform searches and display search result
34private void printSearchResults( String key )
35{
36int result = 0;
37
38System.out.printf( "\nSearching for: %s\n", key );
39result = Collections.binarySearch( list, key );
1 // Fig. 19.15: Algorithms2.java
2 // Using algorithms addAll, frequency and disjoint.
3import java.util.List;
4import java.util.Vector;
5import java.util.Arrays;
6import java.util.Collections;
8public class Algorithms2
9{
10private String[] colors = { "red", "white", "yellow", "blue" };
11private List< String > list;
12private Vector< String > vector = new Vector< String >();
13
14// create List and Vector
15// and manipulate them with methods from Collections
16public Algorithms2()
17{
18// initialize list and vector
19list = Arrays.asList( colors );
20vector.add( "black" );
21vector.add( "red" );
22vector.add( "green" );
23
24 System.out.println( "Before addAll, vector contains: " ); 25
26// display elements in vector
27for ( String s : vector )
28System.out.printf( "%s ", s );
30// add elements in colors to list
31Collections.addAll( vector, colors );
33System.out.println( "\n\nAfter addAll, vector contains: " );
35// display elements in vector
36for ( String s : vector )
37 |
System.out.printf( "%s ", s ); |
38 |
|
39// get frequency of "red"
40int frequency = Collections.frequency( vector, "red" );
41System.out.printf(
42"\n\nFrequency of red in vector: %d\n", frequency );
44// check whether list and vector have elements in common
45boolean disjoint = Collections.disjoint( list, vector );
47System.out.printf( "\nlist and vector %s elements in common\n",
48( disjoint ? "do not have" : "have" ) );
49} // end Algorithms2 constructor
50
51public static void main( String args[] )
52{
53new Algorithms2();
54} // end main
55} // end class Algorithms2
Before addAll, vector contains: black red green
After addAll, vector contains:
black red green red white yellow blue
Frequency of red in vector: 2
list and vector have elements in common
[Page 935]
Line 19 initializes list with elements in array colors, and lines 2022 add Strings "black", "red" and "green" to vector. Line 31 invokes method addAll to add elements in array colors to vector. Line 40 gets the frequency of String "red" in Collection vector using method frequency. Note that lines 4142 use the new printf method to print the frequency. Line 45 invokes method disjoint to test whether Collections list and vector have elements in common.
method returns a Number reference to the removed element. If there are no elements in the Stack, method pop throws an EmptyStackException, which terminates the loop. Class Stack also declares method peek. This method returns the top element of the stack without popping the element off the stack.
Line 49 calls Stack method isEmpty (inherited by Stack from class Vector) to determine whether the stack is empty. If it is empty, the method returns true; otherwise, the method returns false.
Method printStack (lines 4761) uses the enhanced for statement to iterate through the elements in the stack. The current top of the stack (the last value pushed onto the stack) is the first value printed. Because class Stack extends class Vector, the entire public interface of class Vector is available to clients of class Stack.
Error-Prevention Tip 19.1
Because Stack extends Vector, all public Vector methods can be called on Stack objects, even if the methods do not represent conventional stack operations. For example, Vector method add can be used to insert an element anywhere in a stackan operation that could "corrupt" the stack. When manipulating a Stack, only methods push and pop should be used to add elements to and remove elements from the Stack, respectively.
Line 10 creates a PriorityQueue that stores Doubles with an initial capacity of 11 elements and orders the elements according to the object's natural ordering (the defaults for a PriorityQueue). Note that PriorityQueue is a generic class and that line 10 instantiates a PriorityQueue with a type argument Double. Class PriorityQueue provides five additional constructors. One of these takes an int and a Comparator object to create a PriorityQueue with the initial capacity specified by the int and the ordering by the Comparator. Lines 1315 use method offer to add elements to the priority queue. Method offer throws a NullPointException if the program attempts to add a null object to the queue. The loop in lines 2024 use method size to determine whether the priority queue is empty (line 20). While there are more elements, line 22 uses PriorityQueue method peek to retrieve the highest-priority element in the queue for output (without actually removing the element from the queue). Line 23 removes the highest-priority element in the queue with method poll.
[Page 939]
[Page 939 (continued)]
19.9. Sets
A Set is a Collection that contains unique elements (i.e., no duplicate elements). The collections framework contains several Set implementations, including HashSet and TreeSet. HashSet stores its elements in a hash table, and TReeSet stores its elements in a tree. The concept of hash tables is presented in Section 19.10. Figure 19.18 uses a HashSet to remove duplicate strings from a List. Recall that both List and Collection are generic types, so line 18 creates a List that contains String objects,
and line 24 passes a Collection of Strings to method printNonDuplicates.
Figure 19.18. HashSet used to remove duplicate values from array of strings.
(This item is displayed on page 940 in the print version)
1 // Fig. 19.18: SetTest.java
2 // Using a HashSet to remove duplicates.
3import java.util.List;
4import java.util.Arrays;
5import java.util.HashSet;
6import java.util.Set;
7import java.util.Collection;
9public class SetTest
10{
11private static final String colors[] = { "red", "white", "blue",
12"green", "gray", "orange", "tan", "white", "cyan",
13"peach", "gray", "orange" };
14
15// create and output ArrayList
16public SetTest()
17{
18List< String > list = Arrays.asList( colors );
19System.out.printf( "ArrayList: %s\n", list );
20printNonDuplicates( list );
21} // end SetTest constructor
23// create set from array to eliminate duplicates
24private void printNonDuplicates( Collection< String > collection )
25{
26// create a HashSet
27Set< String > set = new HashSet< String >( collection );
29System.out.println( "\nNonduplicates are: " );
31for ( String s : set )
32 |
System.out.printf( "%s ", s ); |
33 |
|
34System.out.println();
35} // end method printNonDuplicates
37public static void main( String args[] )
38{
39new SetTest();
40} // end main
41} // end class SetTest
ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange]
Nonduplicates are:
