0% found this document useful (0 votes)
46 views

Algorithms Sorting

This document summarizes Chapter 21 of a textbook on Java collections. It introduces the Java collections framework, which provides reusable components for common data structures like lists, sets, and maps. It describes the Collection interface and subclasses like List and Set. It also discusses how the Arrays class provides methods for manipulating and searching arrays, including sort, fill, equals and binarySearch. Methods of the Collections class are used to implement common algorithms on collections like sort, shuffle and search.

Uploaded by

Lawrence Ngari
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Algorithms Sorting

This document summarizes Chapter 21 of a textbook on Java collections. It introduces the Java collections framework, which provides reusable components for common data structures like lists, sets, and maps. It describes the Collection interface and subclasses like List and Set. It also discusses how the Arrays class provides methods for manipulating and searching arrays, including sort, fill, equals and binarySearch. Methods of the Collections class are used to implement common algorithms on collections like sort, shuffle and search.

Uploaded by

Lawrence Ngari
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Chapter 21 – Collections

Outline
21.1 Introduction
21.2 Collections Overview
21.3 Class Arrays
21.4 Interface Collection and Class Collections
21.5 Lists
21.6 Algorithms
21.6.1 Algorithm sort
21.6.2 Algorithm shuffle
21.6.3 Algorithms reverse, fill, copy, max and min
21.6.4 Algorithm binarySearch
21.7 Sets
21.8 Maps
21.9 Synchronization Wrappers
21.10 Unmodifiable Wrappers
21.11 Abstract Implementations
21.12 (Optional) Discovering Design Patterns: Design Patterns Used in
Package java.util

 2002 Prentice Hall, Inc. All rights reserved.


21.1 Introduction

• Java collections framework


– Provides reusable componentry
– Existing data structures
• Example of code reuse

 2002 Prentice Hall, Inc. All rights reserved.


21.2 Collections Overview

• Collection
– Data structure (object) that can hold other objects
• Collections framework
– Interfaces that define operations for various collection types
– Belong to package java.util
• Collection
• Set
• List
• Map

 2002 Prentice Hall, Inc. All rights reserved.


21.3 Class Arrays

• Class Arrays
– Provides static methods for manipulating arrays
– Provides “high-level” methods
• Method binarySearch for searching sorted arrays
• Method equals for comparing arrays
• Method fill for placing values into arrays
• Method sort for sorting arrays

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.1: UsingArrays.java Outline
2 // Using Java arrays.
3
4 // Java core packages
5 import java.util.*; Fig. 21.1 Using
6 methods of class
7 public class UsingArrays { Arrays.
8 private int intValues[] = { 1, 2, 3, 4, 5, 6 };
9 private double doubleValues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 };
10 private int filledInt[], intValuesCopy[]; Line 18
11
12 // initialize arrays
13 public UsingArrays() Line 20
14 { Use static method
15 filledInt = new int[ 10 ]; fill Lines Arrays
of class22-23
16 intValuesCopy = new int[ intValues.length ]; to populate array with 7s
17
18 Arrays.fill( filledInt, 7 ); // fill with 7s
19 Use static method
20 Arrays.sort( doubleValues ); // sort doubleValues
21
sort of class Arrays
22 System.arraycopy( intValues, 0, intValuesCopy, to sort array’s elements
23 0, intValues.length ); in ascending order
24 }
25
26 // output values in each array Use static method arraycopy of
27 public void printArrays()
28 { class System to copy array intValues
29 System.out.print( "doubleValues: " ); into array intValuesCopy
30
31 for ( int count = 0; count < doubleValues.length; count++ )
32 System.out.print( doubleValues[ count ] + " " );
33
34 System.out.print( "\nintValues: " );
35
 2002 Prentice Hall, Inc.
All rights reserved.
36 for ( int count = 0; count < intValues.length; count++ ) Outline
37 System.out.print( intValues[ count ] + " " );
38
39 System.out.print( "\nfilledInt: " );
40 Fig. 21.1 Using
41 for ( int count = 0; count < filledInt.length; count++ ) methods of class
42 System.out.print( filledInt[ count ] + " " ); Arrays. (Part 2)
43
44 System.out.print( "\nintValuesCopy: " );
45 Line 55
46 for ( int count = 0; count < intValuesCopy.length; count++ )
47 System.out.print( intValuesCopy[ count ] + " " );
48 Lines 61 and 66
49 System.out.println();
50 }
51
52 // find value in array intValues
53 public int searchForInt( int value )
54 { Use static method
55 return Arrays.binarySearch( intValues, value ); binarySearch of class Arrays
56 } to perform binary search on array
57
58 // compare array contents
59 public void printEquality()
60 {
61 boolean b = Arrays.equals( intValues, intValuesCopy ); Use static method equals
62
63 System.out.println( "intValues " + ( b ? "==" : "!=" ) of class Arrays to determine
64 + " intValuesCopy" ); whether values of the two
65 arrays are equivalent
66 b = Arrays.equals( intValues, filledInt );
67
68 System.out.println( "intValues " + ( b ? "==" : "!=" )
69 + " filledInt" );
70 }
 2002 Prentice Hall, Inc.
All rights reserved.
71 Outline
72 // execute application
73 public static void main( String args[] )
74 {
75 UsingArrays usingArrays = new UsingArrays(); Fig. 21.1 Using
76 methods of class
77 usingArrays.printArrays(); Arrays. (Part 3)
78 usingArrays.printEquality();
79
80 int location = usingArrays.searchForInt( 5 );
81 System.out.println( ( location >= 0 ?
82 "Found 5 at element " + location : "5 not found" ) +
83 " in intValues" );
84
85 location = usingArrays.searchForInt( 8763 );
86 System.out.println( ( location >= 0 ?
87 "Found 8763 at element " + location :
88 "8763 not found" ) + " in intValues" );
89 }
90
91 } // end class UsingArrays

doubleValues: 0.2 3.4 7.9 8.4 9.3


intValues: 1 2 3 4 5 6
filledInt: 7 7 7 7 7 7 7 7 7 7
intValuesCopy: 1 2 3 4 5 6
intValues == intValuesCopy
intValues != filledInt
Found 5 at element 4 in intValues
8763 not found in intValues

 2002 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 21.2: UsingAsList.java Outline
2 // Using method asList
3
4 // Java core packages
5 import java.util.*; Fig. 21.2 Using
6 static method
7 public class UsingAsList { asList.
8 private String values[] = { "red", "white", "blue" };
9 private List list;
10 Use static Line 14 asList
method
11 // initialize List and set value at location 1 of class Arrays to return
12 public UsingAsList()
13 { List viewLine 15 values
of array
14 list = Arrays.asList( values ); // get List
15 list.set( 1, "green" ); // change a value Lineset
23 of List
Use method
16 }
17 object to change the contents
18 // output List and array of element 1 to
Line 24"green"
19 public void printElements()
20 {
21 System.out.print( "List elements : " ); List method size returns
22 number of elements in List
23 for ( int count = 0; count < list.size(); count++ )
24 System.out.print( list.get( count ) + " " );
25 List method get returns
26 System.out.print( "\nArray elements: " );
27 individual element in List
28 for ( int count = 0; count < values.length; count++ )
29 System.out.print( values[ count ] + " " );
30
31 System.out.println();
32 }
33
 2002 Prentice Hall, Inc.
All rights reserved.
34 // execute application Outline
35 public static void main( String args[] )
36 {
37 new UsingAsList().printElements();
38 } Fig. 21.2 Using
39 static method
40 } // end class UsingAsList asList. (Part 2)
List elements : red green blue
Array elements: red green blue

 2002 Prentice Hall, Inc.


All rights reserved.
21.4 Interface Collection and Class
Collections
• Interface Collection
– Contains bulk operations
• Adding, clearing, comparing and retaining objects
– Interfaces Set and List extend interface Collection
• Class Collections
– Provides static methods that manipulate collections
– Collections can be manipulated polymorphically

 2002 Prentice Hall, Inc. All rights reserved.


21.5 Lists

• List
– Ordered Collection that can contain duplicate elements
– Sometimes called a sequence
– Implemented via interface List
• ArrayList
• LinkedList
• Vector

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.3: CollectionTest.java Outline
2 // Using the Collection interface
3
4 // Java core packages
5 import java.awt.Color; Fig. 21.3 Using an
6 import java.util.*; ArrayList to
7 demonstrate
8 public class CollectionTest {
9 private String colors[] = { "red", "white", "blue" }; interface
10 Collection.
11 // create ArrayList, add objects to it and manipulate it
12 public CollectionTest()
13 { Lines 17-22
14 ArrayList list = new ArrayList();
15 Line 28
16 // add objects to list
17 list.add( Color.magenta ); // add a color object
18 Line 31
19 for ( int count = 0; count < colors.length; count++ ) Use List method add to
20 list.add( colors[ count ] );
21
add objects to ArrayList
22 list.add( Color.cyan ); // add a color object
23
24 // output list contents
25 System.out.println( "\nArrayList: " ); List method get returns
26 individual element in List
27 for ( int count = 0; count < list.size(); count++ )
28 System.out.print( list.get( count ) + " " );
29 Method removeStrings takes a
30 // remove all String objects
31 removeStrings( list );
Collection as an argument; Line 31
32 passes List, which extends
33 // output list contents Collection, to this method
34 System.out.println( "\n\nArrayList after calling" +
35 " removeStrings: " );
 2002 Prentice Hall, Inc.
All rights reserved.
36 Outline
37 for ( int count = 0; count < list.size(); count++ )
38 System.out.print( list.get( count ) + " " );
39 }
40 Fig. 21.3 Using an
41 // remove String objects from Collection ArrayList to
42 public void removeStrings( Collection collection ) demonstrate
43 {
44 // get iterator interface
45 Iterator iterator = collection.iterator(); Collection.
Obtain Collection iterator
46 (Part 2)
47 // loop while collection has items
48 while ( iterator.hasNext() )
Iterator method hasNext
49 determines whether 45 Iterator
Line the
50 if ( iterator.next() instanceof String ) contains more elements
51 iterator.remove(); // remove String object
52 } Line 48
53 Iterator method next returns
54 // execute application next ObjectLinein Iterator
50
55 public static void main( String args[] )
56 {
57 new CollectionTest(); Use IteratorLine 51 remove to
method
58 } remove String from Iterator
59
60 } // end class CollectionTest

ArrayList:
java.awt.Color[r=255,g=0,b=255] red white blue java.awt.Color
[r=0,g=255,b=255]

ArrayList after calling removeStrings:


java.awt.Color[r=255,g=0,b=255] java.awt.Color[r=0,g=255,b=255]

 2002 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 21.4: ListTest.java Outline
2 // Using LinkLists
3
4 // Java core packages
5 import java.util.*; Fig. 21.4 Using
6 Lists and
7 public class ListTest { ListIterators.
8 private String colors[] = { "black", "yellow", "green",
9 "blue", "violet", "silver" };
10 private String colors2[] = { "gold", "white", "brown", Lines 16-17
11 "blue", "gray", "silver" };
12
13 // set up and manipulate LinkedList objects Line 25
14 public ListTest()
15 { Line 26
16 LinkedList link = new LinkedList();
17 LinkedList link2 = new LinkedList(); Create two LinkedList objects
18
19 // add elements to each list
20 for ( int count = 0; count < colors.length; count++ ) {
21 link.add( colors[ count ] ); Use LinkedList method
22 link2.add( colors2[ count ] ); addAll to append link2
23 }
24
elements to link
25 link.addAll( link2 ); // concatenate lists
26 link2 = null; // release resources
27 Nullify link2, so it can be
28 printList( link ); garbage collected
29
30 uppercaseStrings( link );
31
32 printList( link );
33
34 System.out.print( "\nDeleting elements 4 to 6..." );
35 removeItems( link, 4, 7 );
 2002 Prentice Hall, Inc.
All rights reserved.
36 Outline
37 printList( link );
38 }
39
40 // output List contents Fig. 21.4 Using
Use List method getLists
to obtain
andobject
41 public void printList( List list )
42 { in LinkedList, then print its value
ListIterators.
43 System.out.println( "\nlist: " );
44 (Part 2)
45 for ( int count = 0; count < list.size(); count++ )
46 System.out.print( list.get( count ) + " " ); Lines 41-49
47
48 System.out.println();
49 } Use ListIterator to traverse
Lines 52-63
50 LinkedList elements and convert them to
51 // locate String objects and convert to uppercase upper case (if elements are Strings)
52 public void uppercaseStrings( List list ) Lines 66-69
53 {
54 ListIterator iterator = list.listIterator();
55
56 while ( iterator.hasNext() ) {
57 Object object = iterator.next(); // get item
58
59 if ( object instanceof String ) // check for String
60 iterator.set( Use List method subList and clear
61 ( ( String ) object ).toUpperCase() );
62 } methods to remove LinkedList elements
63 }
64
65 // obtain sublist and use clear method to delete sublist items
66 public void removeItems( List list, int start, int end )
67 {
68 list.subList( start, end ).clear(); // remove items
69 }
70
 2002 Prentice Hall, Inc.
All rights reserved.
71 // execute application Outline
72 public static void main( String args[] )
73 {
74 new ListTest();
75 } Fig. 21.4 Using
76 Lists and
77 } // end class ListTest ListIterators.
(Part 3)
list:
black yellow green blue violet silver gold white brown blue gray silver

list:
BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER

Deleting elements 4 to 6...


list:
BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER

 2002 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 21.5: UsingToArray.java Outline
2 // Using method toArray
3
4 // Java core packages
5 import java.util.*; Fig. 21.5 Using
6 method toArray.
7 public class UsingToArray {
8
9 // create LinkedList, add elements and convert to array Lines 23-24
10 public UsingToArray()
11 {
12 LinkedList links;
13 String colors[] = { "black", "blue", "yellow" };
14
15 links = new LinkedList( Arrays.asList( colors ) );
16
17 links.addLast( "red" ); // add as last item
18 links.add( "pink" ); // add to the end
19 links.add( 3, "green" ); // add at 3rd index
20 links.addFirst( "cyan" ); // add as first item
21
22 // get LinkedList elements as an array
23 colors = ( String [] ) links.toArray( Use List method toArray to obtain
24 new String[ links.size() ] ); array representation of LinkedList
25
26 System.out.println( "colors: " );
27
28 for ( int count = 0; count < colors.length; count++ )
29 System.out.println( colors[ count ] );
30 }
31

 2002 Prentice Hall, Inc.


All rights reserved.
32 // execute application Outline
33 public static void main( String args[] )
34 {
35 new UsingToArray();
36 } Fig. 21.5 Using
37 method toArray.
38 } // end class UsingToArray (Part 2)
colors:
cyan
black
blue
yellow
green
red
pink

 2002 Prentice Hall, Inc.


All rights reserved.
21.6 Algorithms

• Collections Framework provides set of algorithms


– Implemented as static methods
• List algorithms
– sort
– binarySearch
– reverse
– shuffle
– fill
– copy
• Collection algorithms
– min
– max

 2002 Prentice Hall, Inc. All rights reserved.


21.6.1 Algorithm sort

• sort
– Sorts List elements
• Order is determined by natural order of elements’ type
• Relatively fast

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.6: Sort1.java Outline
2 // Using algorithm sort
3
4 // Java core packages
5 import java.util.*; Fig. 21.6 Using
6 algorithm sort.
7 public class Sort1 {
8 private static String suits[] =
9 { "Hearts", "Diamonds", "Clubs", "Spades" }; Line 15
10
11 // display array elements Line 21
12 public void printElements()
13 {
14 // create ArrayList
15 ArrayList list = new ArrayList( Arrays.asList( suits ) ); Create ArrayList
16
17 // output list
18 System.out.println( "Unsorted array elements:\n" + list );
19
20 // sort ArrayList
21 Collections.sort( list ); Use Collections method
22 sort to sort ArrayList
23 // output list
24 System.out.println( "Sorted array elements:\n" + list );
25 }
26
27 // execute application
28 public static void main( String args[] )
29 {
30 new Sort1().printElements();
31 }
32
33 } // end class Sort1
 2002 Prentice Hall, Inc.
All rights reserved.
Unsorted array elements: Outline
[Hearts, Diamonds, Clubs, Spades]
Sorted array elements:
[Clubs, Diamonds, Hearts, Spades]
Fig. 21.6 Using
algorithm sort.
(Part 2)

 2002 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 21.7: Sort2.java Outline
2 // Using a Comparator object with algorithm sort
3
4 // Java core packages
5 import java.util.*; Fig. 21.7 Using a
6 Comparator object
7 public class Sort2 { in sort.
8 private static String suits[] =
9 { "Hearts", "Diamonds", "Clubs", "Spades" };
10 Line 21
11 // output List elements Method reverseOrder of class
12 public void printElements()
13 { CollectionsLine 21returns a
14 // create List Comparator object that represents
15 List list = Arrays.asList( suits ); the collection’s reverse order
16
17 // output List elements
18 System.out.println( "Unsorted array elements:\n" + list );
19
20 // sort in descending order using a comparator
21 Collections.sort( list, Collections.reverseOrder() );
22
23 // output List elements
24 System.out.println( "Sorted list elements:\n" + list );
25 }
26
27 // execute application
28 public static void main( String args[] ) Method sort of class Collections can use a
29 { Comparator object to sort a List
30 new Sort2().printElements();
31 }
32
33 } // end class Sort2
 2002 Prentice Hall, Inc.
All rights reserved.
Unsorted array elements: Outline
[Hearts, Diamonds, Clubs, Spades]
Sorted list elements:
[Spades, Hearts, Diamonds, Clubs]
Fig. 21.7 Using a
Comparator object
in sort. (Part 2)

 2002 Prentice Hall, Inc.


All rights reserved.
21.6.2 Algorithm shuffle

• shuffle
– Randomly orders List elements

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.8: Cards.java Outline
2 // Using algorithm shuffle
3
4 // Java core packages
5 import java.util.*; Fig. 21.8 Card
6 shuffling and
7 // class to represent a Card in a deck of cards dealing example.
8 class Card {
9 private String face;
10 private String suit;
11
12 // initialize a Card
13 public Card( String initialface, String initialSuit )
14 {
15 face = initialface;
16 suit = initialSuit;
17 }
18
19 // return face of Card
20 public String getFace()
21 {
22 return face;
23 }
24
25 // return suit of Card
26 public String getSuit()
27 {
28 return suit;
29 }
30
31 // return String representation of Card
32 public String toString()
33 {
34 StringBuffer buffer =
35 new StringBuffer( face + " of " + suit );
 2002 Prentice Hall, Inc.
All rights reserved.
36 Outline
37 buffer.setLength( 20 );
38
39 return buffer.toString();
40 } Fig. 21.8 Card
41 shuffling and
42 } // end class Card dealing example.
43
44 // class Cards definition (Part 2)
45 public class Cards {
46 private static String suits[] = Line 63
47 { "Hearts", "Clubs", "Diamonds", "Spades" };
48 private static String faces[] = { "Ace", "Deuce", "Three",
49 "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
50 "Jack", "Queen", "King" };
51 private List list;
52
53 // set up deck of Cards and shuffle
54 public Cards()
55 {
56 Card deck[] = new Card[ 52 ];
57
58 for ( int count = 0; count < deck.length; count++ )
59 deck[ count ] = new Card( faces[ count % 13 ],
60 suits[ count / 13 ] );
61
62 list = Arrays.asList( deck ); // get List
63 Collections.shuffle( list ); // shuffle deck
64 }
65 Use method shuffle of class
66 // output deck
67 public void printCards() Collections to shuffle List
68 {
69 int half = list.size() / 2 - 1;
70
 2002 Prentice Hall, Inc.
All rights reserved.
71 for ( int i = 0, j = half; i <= half; i++, j++ ) Outline
72 System.out.println(
73 list.get( i ).toString() + list.get( j ) );
74 }
75 Fig. 21.8 Card
76 // execute application shuffling and
77 public static void main( String args[] ) dealing example.
78 {
79 new Cards().printCards(); (Part 3)
80 }
81
82 } // end class Cards

 2002 Prentice Hall, Inc.


All rights reserved.
King of Diamonds Ten of Spades Outline
Deuce of Hearts Five of Spades
King of Clubs Five of Clubs
Jack of Diamonds Jack of Spades
King of Spades Ten of Clubs Fig. 21.8 Card
Six of Clubs Three of Clubs shuffling and
Seven of Clubs Jack of Clubs dealing example.
Seven of Hearts Six of Spades
Eight of Hearts Six of Diamonds (Part 4)
King of Hearts Nine of Diamonds
Ace of Hearts Four of Hearts
Jack of Hearts Queen of Diamonds
Queen of Clubs Six of Hearts
Seven of Diamonds Ace of Spades
Three of Spades Deuce of Spades
Seven of Spades Five of Diamonds
Ten of Hearts Queen of Hearts
Ten of Diamonds Eight of Clubs
Nine of Spades Three of Diamonds
Four of Spades Ace of Clubs
Four of Clubs Four of Diamonds
Nine of Clubs Three of Hearts
Eight of Diamonds Deuce of Diamonds
Deuce of Clubs Nine of Hearts
Eight of Spades Five of Hearts
Ten of Spades Queen of Spades

 2002 Prentice Hall, Inc.


All rights reserved.
21.6.3 Algorithms reverse, fill, copy,
max and min
• reverse
– Reverses the order of List elements
• fill
– Populates List elements with values
• copy
– Creates copy of a List
• max
– Returns largest element in List
• min
– Returns smallest element in List

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.9: Algorithms1.java Outline
2 // Using algorithms reverse, fill, copy, min and max
3
4 // Java core packages
5 import java.util.*; Fig. 21.9 Using
6 algorithms
7 public class Algorithms1 { reverse, fill,
8 private String letters[] = { "P", "C", "M" }, lettersCopy[];
9 private List list, copyList; copy, max and min.
10
11 // create a List and manipulate it with algorithms from Line 22
12 // class Collections
13 public Algorithms1()
14 { Line 27
15 list = Arrays.asList( letters ); // get List
16 lettersCopy = new String[ 3 ];
17 copyList = Arrays.asList( lettersCopy ); Line 34
18 Use method reverse of
19 System.out.println( "Printing initial statistics: " );
20 printStatistics( list ); class Collections to
21 obtain List in reverse order
22 Collections.reverse( list ); // reverse order
23 System.out.println( "\nPrinting statistics after " +
24 "calling reverse: " ); Use method copy of class
25 printStatistics( list ); Collections to obtain copy of List
26
27 Collections.copy( copyList, list ); // copy List
28 System.out.println( "\nPrinting statistics after " +
29 "copying: " );
30 printStatistics( copyList );
31
32 System.out.println( "\nPrinting statistics after " +
33 "calling fill: " );
34 Collections.fill( list, "R" ); Use method fill of class Collections
 2002 Prentice Hall, Inc.
35 printStatistics( list ); to populate List with the letter "R"
All rights reserved.
36 } Outline
37
38 // output List information
39 private void printStatistics( List listRef )
40 { Fig. 21.9 Using
41 System.out.print( "The list is: " ); algorithms
42 reverse, fill,
43 for ( int k = 0; k < listRef.size(); k++ ) Obtain maximum value in List
44 System.out.print( listRef.get( k ) + " " ); copy, max and min.
45 (Part 2)
46 System.out.print( "\nMax: " + Collections.max( listRef ) );
47 System.out.println(
48 " Min: " + Collections.min( listRef ) ); Line 46
49 }
50
51 // execute application Obtain minimumLine
value48
in List
52 public static void main( String args[] )
53 {
54 new Algorithms1();
55 }
56
57 } // end class Algorithms1

Printing initial statistics:


The list is: P C M
Max: P Min: C
Printing statistics after calling reverse:
The list is: M C P
Max: P Min: C
Printing statistics after copying:
The list is: M C P
Max: P Min: C
Printing statistics after calling fill:
The list is: R R R
Max: R Min: R  2002 Prentice Hall, Inc.
All rights reserved.
21.6.4 Algorithm binarySearch

• binarySearch
– Locates Object in List
• Returns index of Object in List if Object exists
• Returns negative value if Object does not exist

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.10: BinarySearchTest.java Outline
2 // Using algorithm binarySearch
3
4 // Java core packages
5 import java.util.*; Fig. 21.10 Using
6 algorithm
7 public class BinarySearchTest { binarySearch.
8 private String colors[] = { "red", "white", "blue", "black",
9 "yellow", "purple", "tan", "pink" };
10 private ArrayList list; // ArrayList reference Line 16
11
12 // create, sort and output list
13 public BinarySearchTest()
14 {
15 list = new ArrayList( Arrays.asList( colors ) );
16 Collections.sort( list ); // sort the ArrayList Sort List in ascending order
17 System.out.println( "Sorted ArrayList: " + list );
18 }
19
20 // search list for various values
21 public void printSearchResults()
22 {
23 printSearchResultsHelper( colors[ 3 ] ); // first item
24 printSearchResultsHelper( colors[ 0 ] ); // middle item
25 printSearchResultsHelper( colors[ 7 ] ); // last item
26 printSearchResultsHelper( "aardvark" ); // below lowest
27 printSearchResultsHelper( "goat" ); // does not exist
28 printSearchResultsHelper( "zebra" ); // does not exist
29 }
30
31 // helper method to perform searches
32 private void printSearchResultsHelper( String key )
33 {
34 int result = 0;
35
 2002 Prentice Hall, Inc.
All rights reserved.
36 System.out.println( "\nSearching for: " + key ); Outline
37 result = Collections.binarySearch( list, key );
38 System.out.println(
39 ( result >= 0 ? "Found at index " + result :
40 "Not Found (" + result + ")" ) ); binarySearch
Use methodFig. 21.10 Using
41 } of class Collections
algorithm to
42 search List for specified key
binarySearch.
43 // execute application
44 public static void main( String args[] ) (Part 2)
45 {
46 new BinarySearchTest().printSearchResults(); Line 37
47 }
48
49 } // 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: aardvark


Not Found (-1)

Searching for: goat


Not Found (-3)

Searching for: zebra


Not Found (-9)
 2002 Prentice Hall, Inc.
All rights reserved.
21.7 Sets

• Set
– Collection that contains unique elements
– HashSet
• Stores elements in hash table
– TreeSet
• Stores elements in tree

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.11: SetTest.java Outline
2 // Using a HashSet to remove duplicates
3
4 // Java core packages
5 import java.util.*; Fig. 21.11 Using a
6 HashSet to remove
7 public class SetTest { duplicates.
8 private String colors[] = { "red", "white", "blue",
9 "green", "gray", "orange", "tan", "white", "cyan",
10 "peach", "gray", "orange" }; Line 26
11
12 // create and output ArrayList
13 public SetTest() Lines 31-32
14 {
15 ArrayList list;
16
17 list = new ArrayList( Arrays.asList( colors ) );
18 System.out.println( "ArrayList: " + list );
19 printNonDuplicates( list );
20 }
21
22 // create set from array to eliminate duplicates
23 public void printNonDuplicates( Collection collection )
24 {
25 // create a HashSet and obtain its iterator Create HashSet from
26 HashSet set = new HashSet( collection );
27 Iterator iterator = set.iterator(); Collection object
28
29 System.out.println( "\nNonduplicates are: " );
30 Use Iterator to
31 while ( iterator.hasNext() )
32 System.out.print( iterator.next() + " " ); traverse HashSet and
33 print nonduplicates
34 System.out.println();
35 }
 2002 Prentice Hall, Inc.
All rights reserved.
36 Outline
37 // execute application
38 public static void main( String args[] )
39 {
40 new SetTest(); Fig. 21.11 Using a
41 } HashSet to remove
42 duplicates. (Part 2)
43 } // end class SetTest

ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan,
peach, gray, orange]

Nonduplicates are:
orange cyan green tan white blue peach red gray

 2002 Prentice Hall, Inc.


All rights reserved.
1 // Fig. 21.12: SortedSetTest.java Outline
2 // Using TreeSet and SortedSet
3
4 // Java core packages
5 import java.util.*; Fig. 21.12 Using
6 SortedSets and
7 public class SortedSetTest { TreeSets.
8 private static String names[] = { "yellow", "green", "black",
9 "tan", "grey", "white", "orange", "red", "green" };
10 Line 14
11 // create a sorted set with TreeSet, then manipulate it
12 public SortedSetTest()
13 { Line 21
Create TreeSet
14 TreeSet tree = new TreeSet( Arrays.asList( names ) );
15 from names array
Line 25
16 System.out.println( "set: " );
17 printSet( tree );
18 Lines 28-29
19 // get headSet based upon "orange"
20 System.out.print( "\nheadSet (\"orange\"): " ); Use TreeSet method
21 printSet( tree.headSet( "orange" ) ); headSet to get TreeSet
22
23 // get tailSet based upon "orange" subset less than "orange"
24 System.out.print( "tailSet (\"orange\"): " );
25 printSet( tree.tailSet( "orange" ) ); Use TreeSet method
26 tailSet to get TreeSet
27 // get first and last elements
28 System.out.println( "first: " + tree.first() ); subset greater than "orange"
29 System.out.println( "last : " + tree.last() );
30 } Methods first and last obtain
31
32 // output set smallest and largest TreeSet
33 public void printSet( SortedSet set ) elements, respectively
34 {
35 Iterator iterator = set.iterator();
 2002 Prentice Hall, Inc.
All rights reserved.
36 Outline
Use Iterator to
37 while ( iterator.hasNext() )
38 System.out.print( iterator.next() + " " ); traverse HashSet and
39 print
40 System.out.println(); Fig. values
21.12 Using
41 } SortedSets and
42 TreeSets. (Part 2)
43 // execute application
44 public static void main( String args[] )
45 { Lines 37-38
46 new SortedSetTest();
47 }
48
49 } // end class SortedSetTest

set:
black green grey orange red tan white yellow

headSet ("orange"): black green grey


tailSet ("orange"): orange red tan white yellow
first: black
last : yellow

 2002 Prentice Hall, Inc.


All rights reserved.
21.8 Maps

• Map
– Associates keys to values
– Cannot contain duplicate keys
• Called one-to-one mapping

 2002 Prentice Hall, Inc. All rights reserved.


1 // Fig. 21.13: MapTest.java Outline
2 // Using a HashMap to store the number of words that
3 // begin with a given letter
4
5 // Java core packages Fig. 21.13 Using
6 import java.util.*; HashMaps and
7 Maps.
8 public class MapTest {
9 private static String names[] = { "one", "two", "three",
10 "four", "five", "six", "seven", "two", "ten", "four" }; Line 15
11
12 // build a HashMap and output contents
13 public MapTest() Lines 19-20
14 {
15 HashMap map = new HashMap(); Create HashMap Lines 25-31
16 Integer i;
17
18 for ( int count = 0; count < names.length; count++ ) {
19 i = ( Integer ) map.get(
20 new Character( names[ count ].charAt( 0 ) ) );
Use method get to retrieve a
21 Character from HashMap
22 // if key is not in map then give it value one
23 // otherwise increment its value by 1
24 if ( i == null )
25 map.put(
26 new Character( names[ count ].charAt( 0 ) ),
27 new Integer( 1 ) ); Use method put to store a
28 else Character with an
29 map.put( Integer key in HashMap
30 new Character( names[ count ].charAt( 0 ) ),
31 new Integer( i.intValue() + 1 ) );
32 }
33
34 System.out.println(
35 "\nnumber of words beginning with each letter: " );
 2002 Prentice Hall, Inc.
All rights reserved.
36 printMap( map ); Outline
37 }
38
39 // output map contents
40 public void printMap( Map mapRef ) Fig. 21.13 Using
41 { HashMaps and
42 System.out.println( mapRef.toString() ); Maps. (Part 2)
43 System.out.println( "size: " + mapRef.size() );
44 System.out.println( "isEmpty: " + mapRef.isEmpty() );
45 }
46
47 // execute application
48 public static void main( String args[] )
49 {
50 new MapTest();
51 }
52
53 } // end class MapTest

number of words beginning with each letter:


{t=4, s=2, o=1, f=3}
size: 4
isEmpty: false

 2002 Prentice Hall, Inc.


All rights reserved.
21.9 Synchronization Wrappers

• Built-in collections are unsynchronized


– Concurrent access to a Collection can cause errors
– Java provides synchronization wrappers to avoid this
• Via set of public static methods

 2002 Prentice Hall, Inc. All rights reserved.


21.9 Synchronization Wrappers (cont.)

public static method header


Collection synchronizedCollection( Collection c )
List synchronizedList( List aList )
Set synchronizedSet( Set s )
SortedSet synchronizedSortedSet( SortedSet s )
Map synchronizedMap( Map m )
SortedMap synchronizedSortedMap( SortedMap m )
Fig. 21.14 Sync hroniza tion w ra p p e r m ethod s.

 2002 Prentice Hall, Inc. All rights reserved.


21.10 Unmodifiable Wrappers

• Unmodifiable wrappers
– Converting collections to unmodifiable collections
– Throw UnsorrtedOperationException if attempts
are made to modify the collection

 2002 Prentice Hall, Inc. All rights reserved.


21.10 Unmodifiable Wrappers

public static method header


Collection unmodifiableCollection( Collection c )
List unmodifiableList( List aList )
Set unmodifiableSet( Set s )
SortedSet unmodifiableSortedSet( SortedSet s )
Map unmodifiableMap( Map m )
SortedMap unmodifiableSortedMap( SortedMap m )
Fig. 21.15 Unm od ifia b le w ra p p er m e thod s.

 2002 Prentice Hall, Inc. All rights reserved.


21.11 Abstract Implementations

• Abstract implementations
– Offer “bare bones” implementation of collection interfaces
• Programmers can “flesh out” customizable implementations
– AbstractCollection
– AbstractList
– AbstractMap
– AbstractSequentialList
– AbstractSet

 2002 Prentice Hall, Inc. All rights reserved.


21.12 (Optional) Discovering Design
Patterns: Design Patterns Used in
Package java.util
• Prototype design pattern
– Creational design pattern
– Used when system must copy an object but cannot determine
object type until runtime
– Prototype object returns a copy of itself
• Must belong to a class that implements common interface
– The interface’s implementation provides the copy
– Java API provides:
• Method clone of class java.lang.Object
• Interface java.lang.Cloneable

 2002 Prentice Hall, Inc. All rights reserved.


21.12 (Optional) Discovering Design
Patterns: Design Patterns Used in
Package java.util (cont.)
• Iterator design pattern
– Behavioral design pattern
– Allow objects to access objects from data structure without
knowing that data structure’s behavior
• E.g., how the structure stores its objects
• E.g., specifics of traversing the structure
• An object can traverse a linked list and a hash table similarly
– Java provides interface java.util.Iterator

 2002 Prentice Hall, Inc. All rights reserved.

You might also like