Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

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 );

40

41if ( result >= 0 )

42System.out.printf( "Found at index %d\n", result );

43else

44System.out.printf( "Not Found (%d)\n",result );

45} // end method printSearchResults

46

47public static void main( String args[] )

48{

49BinarySearchTest binarySearchTest = new BinarySearchTest();

50binarySearchTest.search();

51} // end main

52} // end class BinarySearchTest

Sorted ArrayList: [black, blue, pink, purple, red, tan, white, yellow]

Searching

for:

black

Found at

index

0

Searching

for:

red

Found at

index

4

Searching

for:

pink

Found at

index

2

Searching

for: aqua

Not Found (-1)

 

Searching

for: gray

Not Found (-3)

 

Searching

for: teal

Not Found

(-7)

 

Recall that both List and ArrayList are generic types (lines 12 and 17). Collections method binarySearch expects the list's elements to be sorted in ascending order, so line 18 in the constructor sorts the list with Collections method sort. If the list's elements are not sorted, the result is undefined. Line 19 outputs the sorted list. Method search (lines 2331) is called from main to perform the searches. Each search calls method printSearchResults (lines 3445) to perform the search and output the results. Line 39 calls Collections method binarySearch to search list for the specified key. Method binarySearch takes a List as the first argument and an Object as the second argument. Lines 4144 output the results of the search. An overloaded version of binarySearch takes a Comparator object as its third argument, which specifies how binarySearch should compare elements.

[Page 934]

19.6.5. Algorithms addAll, frequency and disjoint

Among others, J2SE 5.0 includes three new algorithms in class Collections, namely addAll, frequency and disjoint. Algorithm addAll takes two argumentsa Collection into which to insert the new element(s) and an array that provides elements to be inserted. Algorithm frequency takes two argumentsa Collection to be searched and an Object to be searched for in the collection. Method frequency returns the number of times that the second argument appears in the collection. Algorithm disjoint takes two Collections and returns true if they have no elements in common. Figure 19.15 demonstrates the use of algorithms addAll, frequency and disjoint.

Figure 19.15. Collections method addAll, frequency and disjoint.

(This item is displayed on pages 934 - 935 in the print version)

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.

[Page 935 (continued)]

19.7. Stack Class of Package java.util

In Chapter 17, Data Structures, we learned how to build fundamental data structures, including linked lists, stacks, queues and trees. In a world of software reuse, rather than building data structures as we need them, we can often take advantage of existing data structures. In this section, we investigate class Stack in the Java utilities package (java.util).

Section 19.5.3 discussed class Vector, which implements a dynamically resizable array. Class Stack extends class Vector to implement a stack data structure. Autoboxing occurs when you add a primitive type to a Stack, because class Stack stores only references to objects. Figure 19.16 demonstrates several Stack methods. For the details of class Stack, visit java.sun.com/j2se/5.0/docs/api/java/util/Stack.html.

Figure 19.16. Stack class of package java.util.

(This item is displayed on pages 936 - 937 in the print version)

1// Fig. 19.16: StackTest.java

2// Program to test java.util.Stack.

3import java.util.Stack;

4import java.util.EmptyStackException;

6public class StackTest

7{

8public StackTest()

9{

10Stack< Number > stack = new Stack< Number >();

12// create numbers to store in the stack

13Long longNumber = 12L;

14Integer intNumber = 34567;

15Float floatNumber = 1.0F;

16Double doubleNumber = 1234.5678;

18// use push method

19stack.push( longNumber ); // push a long

20printStack( stack );

21stack.push( intNumber ); // push an int

22printStack( stack );

23stack.push( floatNumber ); // push a float

24printStack( stack );

25stack.push( doubleNumber ); // push a double

26printStack( stack );

28// remove items from stack

29try

30{

31Number removedObject = null;

33// pop elements from stack

34while ( true )

35{

36

removedObject = stack.pop(); // use pop method

37

System.out.printf( "%s popped\n", removedObject );

38

printStack( stack );

39} // end while

40} // end try

41catch ( EmptyStackException emptyStackException )

42{

43emptyStackException.printStackTrace();

44} // end catch

45} // end StackTest constructor

46

47 private void printStack( Stack< Number > stack )

48{

49if ( stack.isEmpty() )

50System.out.print( "stack is empty\n\n" ); // the stack is empty

51else // stack is not empty

52{

53System.out.print( "stack contains: " );

54

55// iterate through the elements

56for ( Number number : stack )

57

System.out.printf( "%s ", number );

58

 

59System.out.print( "(top) \n\n" ); // indicates top of the stack

60} // end else

61} // end method printStack

62

63public static void main( String args[] )

64{

65new StackTest();

66} // end main

67} // end class StackTest

stack contains: 12 (top)

stack contains: 12 34567 (top) stack contains: 12 34567 1.0 (top)

stack contains: 12 34567 1.0 1234.5678 (top)

1234.5678 popped

stack contains: 12 34567 1.0 (top)

1.0 popped

stack contains: 12 34567 (top)

34567 popped

stack contains: 12 (top)

12 popped stack is empty

java.util.EmptyStackException

at java.util.Stack.peek(Unknown Source) at java.util.Stack.pop(Unknown Source) at StackTest.<init>(StackTest.java:36) at StackTest.main(StackTest.java:65)

[Page 937]

Line 10 of the constructor creates an empty Stack of type Number. Class Number (in package java.lang) is the superclass of most wrapper classes (e.g., Integer, Double) for the primitive types. By creating a Stack of Number, objects of any class that extends the Number class can be pushed onto the stack. Lines 19, 21, 23 and 25 each call Stack method push to add objects to the top of the stack. Note the literals 12L (line 13) and 1.0F (line 15). Any integer literal that has the suffix L is a long value. An integer literal without a suffix is an int value. Similarly, any floating-point literal that has the suffix F is a float value. A floating-point literal without a suffix is a double value. You can learn more about numeric literals in the Java Language Specification at java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#224125.

[Page 938]

An infinite loop (lines 3439) calls Stack method pop to remove the top element of the stack. The

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.

[Page 938 (continued)]

19.8. Class PriorityQueue and Interface Queue

In Section 17.8, we introduced the queue data structure and created our own implementation of it. In this section we investigate interface Queue and class PriorityQueue in the Java utilities package (java.util). Queue, a new collection interface introduced in J2SE 5.0, extends interface Collection and provides additional operations for inserting, removing and inspecting elements in a queue. PriorityQueue, one of the classes that implements the Queue interface, orders elements by their natural ordering as specified by Comparable elements' compareTo method or by a Comparator object that is supplied through the constructor.

Class PriorityQueue provides functionality that enables insertions in sorted order into the underlying data structure and deletions from the front of the underlying data structure. When adding elements to a PriorityQueue, the elements are inserted in priority order such that the highest-priority element (i.e., the largest value) will be the first element removed from the PriorityQueue.

The common PriorityQueue operations are offer to insert an element at the appropriate location based on priority order, poll to remove the highest-priority element of the priority queue (i.e., the head of the queue), peek to get a reference to the highest-priority element of the priority queue (without removing that element), clear to remove all elements in the priority queue and size to get the number of elements in the priority queue. Figure 19.17 demonstrates the PriorityQueue class.

Figure 19.17. PriorityQueue test program.

 

 

(This item is displayed on page 939 in the print version)

1

//

Fig. 19.17: PriorityQueueTest.java

2

//

Standard library class PriorityQueue test program.

3

import java.util.PriorityQueue;

4

 

 

5public class PriorityQueueTest

6{

7public static void main( String args[] )

8{

9// queue of capacity 11

10PriorityQueue< Double > queue = new PriorityQueue< Double >();

12// insert elements to queue

13queue.offer( 3.2 );

14queue.offer( 9.8 );

15queue.offer( 5.4 );

17System.out.print( "Polling from queue: " );

19// display elements in queue

20while ( queue.size() > 0 )

21{

22System.out.printf( "%.1f ", queue.peek() ); // view top element

23queue.poll(); // remove top element

24} // end while

25} // end main

26} // end class PriorityQueueTest

Polling from queue: 3.2 5.4 9.8

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: