Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 21 – Collections Outline 21.1 21.2 21.3 21.4 21.5 21.6 21.7 21.8 21.9 21.10 21.11 21.12 Introduction Collections Overview Class Arrays Interface Collection and Class Collections Lists 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 Sets Maps Synchronization Wrappers Unmodifiable Wrappers Abstract Implementations (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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 21.1: UsingArrays.java // Using Java arrays. // Java core packages import java.util.*; public class UsingArrays { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double doubleValues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; private int filledInt[], intValuesCopy[]; // initialize arrays public UsingArrays() { filledInt = new int[ 10 ]; intValuesCopy = new int[ intValues.length ]; Line 18 Line 20 Use static method fill Lines of class22-23 Arrays to populate array with 7s Arrays.fill( filledInt, 7 ); // fill with 7s Arrays.sort( doubleValues ); // sort doubleValues System.arraycopy( intValues, 0, intValuesCopy, 0, intValues.length ); } // output values in each array public void printArrays() { System.out.print( "doubleValues: " ); Fig. 21.1 Using methods of class Arrays. Use static method sort of class Arrays to sort array’s elements in ascending order Use static method arraycopy of class System to copy array intValues into array intValuesCopy for ( int count = 0; count < doubleValues.length; count++ ) System.out.print( doubleValues[ count ] + " " ); System.out.print( "\nintValues: " ); 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Outline for ( int count = 0; count < intValues.length; count++ ) System.out.print( intValues[ count ] + " " ); System.out.print( "\nfilledInt: " ); Fig. 21.1 Using methods of class Arrays. (Part 2) for ( int count = 0; count < filledInt.length; count++ ) System.out.print( filledInt[ count ] + " " ); System.out.print( "\nintValuesCopy: " ); Line 55 for ( int count = 0; count < intValuesCopy.length; count++ ) System.out.print( intValuesCopy[ count ] + " " ); Lines 61 and 66 System.out.println(); } // find value in array intValues public int searchForInt( int value ) { return Arrays.binarySearch( intValues, value ); } Use static method binarySearch of class Arrays to perform binary search on array // compare array contents public void printEquality() { boolean b = Arrays.equals( intValues, intValuesCopy ); System.out.println( "intValues " + ( b ? "==" : "!=" ) + " intValuesCopy" ); b = Arrays.equals( intValues, filledInt ); System.out.println( "intValues " + ( b ? "==" : "!=" ) + " filledInt" ); } Use static method equals of class Arrays to determine whether values of the two arrays are equivalent 2002 Prentice Hall, Inc. All rights reserved. 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 } // execute application public static void main( String args[] ) { UsingArrays usingArrays = new UsingArrays(); usingArrays.printArrays(); usingArrays.printEquality(); Outline Fig. 21.1 Using methods of class Arrays. (Part 3) int location = usingArrays.searchForInt( 5 ); System.out.println( ( location >= 0 ? "Found 5 at element " + location : "5 not found" ) + " in intValues" ); location = usingArrays.searchForInt( 8763 ); System.out.println( ( location >= 0 ? "Found 8763 at element " + location : "8763 not found" ) + " in intValues" ); } // 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 21.2: UsingAsList.java // Using method asList // Java core packages import java.util.*; public class UsingAsList { private String values[] = { "red", "white", "blue" }; private List list; // initialize List and set value at location 1 public UsingAsList() { list = Arrays.asList( values ); // get List list.set( 1, "green" ); // change a value } // output List and array public void printElements() { System.out.print( "List elements : " ); for ( int count = 0; count < list.size(); count++ ) System.out.print( list.get( count ) + " " ); System.out.print( "\nArray elements: " ); Outline Fig. 21.2 Using static method asList. Use static Line method 14 asList of class Arrays to return List viewLine of array 15 values Lineset 23 of List Use method object to change the contents Line 24"green" of element 1 to List method size returns number of elements in List List method get returns individual element in List for ( int count = 0; count < values.length; count++ ) System.out.print( values[ count ] + " " ); System.out.println(); } 2002 Prentice Hall, Inc. All rights reserved. 34 35 36 37 38 39 40 } // execute application public static void main( String args[] ) { new UsingAsList().printElements(); } // end class UsingAsList Outline Fig. 21.2 Using static method 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 21.3: CollectionTest.java // Using the Collection interface // Java core packages import java.awt.Color; import java.util.*; Fig. 21.3 Using an ArrayList to demonstrate interface Collection. public class CollectionTest { private String colors[] = { "red", "white", "blue" }; // create ArrayList, add objects to it and manipulate it public CollectionTest() { ArrayList list = new ArrayList(); // add objects to list list.add( Color.magenta ); Line 28 // add a color object for ( int count = 0; count < colors.length; count++ ) list.add( colors[ count ] ); list.add( Color.cyan ); Lines 17-22 Line 31 Use List method add to add objects to ArrayList // add a color object // output list contents System.out.println( "\nArrayList: " ); for ( int count = 0; count < list.size(); count++ ) System.out.print( list.get( count ) + " " ); // remove all String objects removeStrings( list ); // output list contents System.out.println( "\n\nArrayList after calling" + " removeStrings: " ); List method get returns individual element in List Method removeStrings takes a Collection as an argument; Line 31 passes List, which extends Collection, to this method 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 } Outline for ( int count = 0; count < list.size(); count++ ) System.out.print( list.get( count ) + " " ); } Fig. 21.3 Using an ArrayList to demonstrate interface Collection. Obtain Collection iterator (Part 2) Iterator method hasNext determines whether Line the 45 Iterator contains more elements Line 48 Iterator method next returns next ObjectLine in Iterator 50 // remove String objects from Collection public void removeStrings( Collection collection ) { // get iterator Iterator iterator = collection.iterator(); // loop while collection has items while ( iterator.hasNext() ) if ( iterator.next() instanceof String ) iterator.remove(); // remove String object } // execute application public static void main( String args[] ) { new CollectionTest(); } 51 remove to Use IteratorLine method remove String from Iterator // 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 21.4: ListTest.java // Using LinkLists // Java core packages import java.util.*; public class ListTest { private String colors[] = { "black", "yellow", "green", "blue", "violet", "silver" }; private String colors2[] = { "gold", "white", "brown", "blue", "gray", "silver" }; // set up and manipulate LinkedList objects public ListTest() { LinkedList link = new LinkedList(); LinkedList link2 = new LinkedList(); Lines 16-17 Line 25 Line 26 Create two LinkedList objects // add elements to each list for ( int count = 0; count < colors.length; count++ ) { link.add( colors[ count ] ); link2.add( colors2[ count ] ); } link.addAll( link2 ); link2 = null; Fig. 21.4 Using Lists and ListIterators. // concatenate lists // release resources printList( link ); Use LinkedList method addAll to append link2 elements to link Nullify link2, so it can be garbage collected uppercaseStrings( link ); printList( link ); System.out.print( "\nDeleting elements 4 to 6..." ); removeItems( link, 4, 7 ); 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Outline printList( link ); } Fig. 21.4 Using Use List method getLists to obtain object and in LinkedList, then print its value ListIterators. // output List contents public void printList( List list ) { System.out.println( "\nlist: " ); (Part 2) for ( int count = 0; count < list.size(); count++ ) System.out.print( list.get( count ) + " " ); System.out.println(); } Lines 41-49 Use ListIterator to traverse Lines 52-63 LinkedList elements and convert them to uppercase upper case (if elements are Strings) Lines 66-69 ) // locate String objects and convert to public void uppercaseStrings( List list { ListIterator iterator = list.listIterator(); while ( iterator.hasNext() ) { Object object = iterator.next(); // get item if ( object instanceof String ) // check for String iterator.set( Use List ( ( String ) object ).toUpperCase() ); } method subList and clear methods to remove LinkedList elements } // obtain sublist and use clear method to delete sublist items public void removeItems( List list, int start, int end ) { list.subList( start, end ).clear(); // remove items } 2002 Prentice Hall, Inc. All rights reserved. 71 72 73 74 75 76 77 } // execute application public static void main( String args[] ) { new ListTest(); } // end class ListTest Outline Fig. 21.4 Using Lists and 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Outline // Fig. 21.5: UsingToArray.java // Using method toArray // Java core packages import java.util.*; Fig. 21.5 Using method toArray. public class UsingToArray { // create LinkedList, add elements and convert to array public UsingToArray() { LinkedList links; String colors[] = { "black", "blue", "yellow" }; Lines 23-24 links = new LinkedList( Arrays.asList( colors ) ); links.addLast( "red" ); links.add( "pink" ); links.add( 3, "green" ); links.addFirst( "cyan" ); // // // // add add add add as to at as last item the end 3rd index first item // get LinkedList elements as an array colors = ( String [] ) links.toArray( new String[ links.size() ] ); Use List method toArray to obtain array representation of LinkedList System.out.println( "colors: " ); for ( int count = 0; count < colors.length; count++ ) System.out.println( colors[ count ] ); } 2002 Prentice Hall, Inc. All rights reserved. 32 33 34 35 36 37 38 } // execute application public static void main( String args[] ) { new UsingToArray(); } // end class UsingToArray Outline Fig. 21.5 Using method toArray. (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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Outline // Fig. 21.6: Sort1.java // Using algorithm sort // Java core packages import java.util.*; Fig. 21.6 Using algorithm sort. public class Sort1 { private static String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" }; Line 15 // display array elements public void printElements() { // create ArrayList ArrayList list = new ArrayList( Arrays.asList( suits ) ); Line 21 Create ArrayList // output list System.out.println( "Unsorted array elements:\n" + list ); // sort ArrayList Collections.sort( list ); Use Collections method sort to sort ArrayList // output list System.out.println( "Sorted array elements:\n" + list ); } // execute application public static void main( String args[] ) { new Sort1().printElements(); } } // end class Sort1 2002 Prentice Hall, Inc. All rights reserved. Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted array elements: [Clubs, Diamonds, Hearts, Spades] Outline Fig. 21.6 Using algorithm sort. (Part 2) 2002 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Outline // Fig. 21.7: Sort2.java // Using a Comparator object with algorithm sort // Java core packages import java.util.*; Fig. 21.7 Using a Comparator object in sort. public class Sort2 { private static String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" }; // output List elements public void printElements() { // create List List list = Arrays.asList( suits ); Line 21 Method reverseOrder of class Collections Line 21returns a Comparator object that represents the collection’s reverse order // output List elements System.out.println( "Unsorted array elements:\n" + list ); // sort in descending order using a comparator Collections.sort( list, Collections.reverseOrder() ); // output List elements System.out.println( "Sorted list elements:\n" + list ); } // execute application public static void main( String args[] ) { new Sort2().printElements(); } } Method sort of class Collections can use a Comparator object to sort a List // end class Sort2 2002 Prentice Hall, Inc. All rights reserved. Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted list elements: [Spades, Hearts, Diamonds, Clubs] Outline 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 21.8: Cards.java // Using algorithm shuffle // Java core packages import java.util.*; // class to represent a Card in a deck of cards class Card { private String face; private String suit; Outline Fig. 21.8 Card shuffling and dealing example. // initialize a Card public Card( String initialface, String initialSuit ) { face = initialface; suit = initialSuit; } // return face of Card public String getFace() { return face; } // return suit of Card public String getSuit() { return suit; } // return String representation of Card public String toString() { StringBuffer buffer = new StringBuffer( face + " of " + suit ); 2002 Prentice Hall, Inc. All rights reserved. Outline 36 37 buffer.setLength( 20 ); 38 39 return buffer.toString(); Fig. 21.8 Card 40 } 41 shuffling and 42 } // end class Card dealing example. 43 (Part 2) 44 // class Cards definition 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 Collections to shuffle List 67 public void printCards() 68 { 69 int half = list.size() / 2 - 1; 2002 Prentice Hall, Inc. 70 All rights reserved. 71 72 73 74 75 76 77 78 79 80 81 82 } for ( int i = 0, j = half; i <= half; i++, j++ ) System.out.println( list.get( i ).toString() + list.get( j ) ); } // execute application public static void main( String args[] ) { new Cards().printCards(); } Outline Fig. 21.8 Card shuffling and dealing example. (Part 3) // end class Cards 2002 Prentice Hall, Inc. All rights reserved. King of Diamonds Deuce of Hearts King of Clubs Jack of Diamonds King of Spades Six of Clubs Seven of Clubs Seven of Hearts Eight of Hearts King of Hearts Ace of Hearts Jack of Hearts Queen of Clubs Seven of Diamonds Three of Spades Seven of Spades Ten of Hearts Ten of Diamonds Nine of Spades Four of Spades Four of Clubs Nine of Clubs Eight of Diamonds Deuce of Clubs Eight of Spades Ten of Spades Ten of Spades Five of Spades Five of Clubs Jack of Spades Ten of Clubs Three of Clubs Jack of Clubs Six of Spades Six of Diamonds Nine of Diamonds Four of Hearts Queen of Diamonds Six of Hearts Ace of Spades Deuce of Spades Five of Diamonds Queen of Hearts Eight of Clubs Three of Diamonds Ace of Clubs Four of Diamonds Three of Hearts Deuce of Diamonds Nine of Hearts Five of Hearts Queen of Spades Outline Fig. 21.8 Card shuffling and dealing example. (Part 4) 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 21.9: Algorithms1.java // Using algorithms reverse, fill, copy, min and max // Java core packages import java.util.*; public class Algorithms1 { private String letters[] = { "P", "C", "M" }, lettersCopy[]; private List list, copyList; // create a List and manipulate it with algorithms from // class Collections public Algorithms1() { list = Arrays.asList( letters ); // get List lettersCopy = new String[ 3 ]; copyList = Arrays.asList( lettersCopy ); System.out.println( "Printing initial statistics: " ); printStatistics( list ); Outline Fig. 21.9 Using algorithms reverse, fill, copy, max and min. Line 22 Line 27 Line 34 Use method reverse of class Collections to obtain List in reverse order Collections.reverse( list ); // reverse order System.out.println( "\nPrinting statistics after " + Use method copy of class "calling reverse: " ); printStatistics( list ); Collections to obtain copy of List Collections.copy( copyList, list ); // copy List System.out.println( "\nPrinting statistics after " + "copying: " ); printStatistics( copyList ); System.out.println( "\nPrinting statistics after " + "calling fill: " ); Use method fill of class Collections Collections.fill( list, "R" ); 2002 Prentice Hall, Inc. printStatistics( list ); to populate List with the letter "R" All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 } Outline } // output List information private void printStatistics( List listRef ) { System.out.print( "The list is: " ); for ( int k = 0; k < listRef.size(); k++ ) System.out.print( listRef.get( k ) + " " ); Fig. 21.9 Using algorithms reverse, fill, Obtain maximum value in List copy, max and min. (Part 2) System.out.print( "\nMax: " + Collections.max( listRef ) ); System.out.println( " Min: " + Collections.min( listRef ) ); Line 46 } // execute application public static void main( String args[] ) { new Algorithms1(); } Obtain minimumLine value48 in List // 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 21.10: BinarySearchTest.java // Using algorithm binarySearch // Java core packages import java.util.*; Fig. 21.10 Using algorithm binarySearch. public class BinarySearchTest { private String colors[] = { "red", "white", "blue", "black", "yellow", "purple", "tan", "pink" }; private ArrayList list; // ArrayList reference // create, sort and output list public BinarySearchTest() { list = new ArrayList( Arrays.asList( colors ) ); Collections.sort( list ); // sort the ArrayList System.out.println( "Sorted ArrayList: " + list ); } // search list for various values public void printSearchResults() { printSearchResultsHelper( colors[ 3 ] ); printSearchResultsHelper( colors[ 0 ] ); printSearchResultsHelper( colors[ 7 ] ); printSearchResultsHelper( "aardvark" ); printSearchResultsHelper( "goat" ); printSearchResultsHelper( "zebra" ); } // // // // // // Line 16 Sort List in ascending order first item middle item last item below lowest does not exist does not exist // helper method to perform searches private void printSearchResultsHelper( String key ) { int result = 0; 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 } System.out.println( "\nSearching for: " + key ); result = Collections.binarySearch( list, key ); System.out.println( ( result >= 0 ? "Found at index " + result : "Not Found (" + result + ")" ) ); } // execute application public static void main( String args[] ) { new BinarySearchTest().printSearchResults(); } Outline Use methodFig. binarySearch 21.10 Using of class Collections to algorithm search List for specified key binarySearch. (Part 2) Line 37 // 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 21.11: SetTest.java // Using a HashSet to remove duplicates // Java core packages import java.util.*; public class SetTest { private String colors[] = { "red", "white", "blue", "green", "gray", "orange", "tan", "white", "cyan", "peach", "gray", "orange" }; // create and output ArrayList public SetTest() { ArrayList list; Outline Fig. 21.11 Using a HashSet to remove duplicates. Line 26 Lines 31-32 list = new ArrayList( Arrays.asList( colors ) ); System.out.println( "ArrayList: " + list ); printNonDuplicates( list ); } // create set from array to eliminate duplicates public void printNonDuplicates( Collection collection ) { // create a HashSet and obtain its iterator HashSet set = new HashSet( collection ); Iterator iterator = set.iterator(); Create HashSet from Collection object System.out.println( "\nNonduplicates are: " ); while ( iterator.hasNext() ) System.out.print( iterator.next() + " " ); System.out.println(); } Use Iterator to traverse HashSet and print nonduplicates 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 } // execute application public static void main( String args[] ) { new SetTest(); } // end class SetTest Outline Fig. 21.11 Using a HashSet to remove duplicates. (Part 2) 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 21.12: SortedSetTest.java // Using TreeSet and SortedSet // Java core packages import java.util.*; public class SortedSetTest { private static String names[] = { "yellow", "green", "black", "tan", "grey", "white", "orange", "red", "green" }; Fig. 21.12 Using SortedSets and TreeSets. Line 14 // create a sorted set with TreeSet, then manipulate it public SortedSetTest() { TreeSet tree = new TreeSet( Arrays.asList( names ) ); System.out.println( "set: " ); printSet( tree ); Line 21 Create TreeSet from names array Line 25 Lines 28-29 // get headSet based upon "orange" System.out.print( "\nheadSet (\"orange\"): printSet( tree.headSet( "orange" ) ); // get tailSet based upon "orange" System.out.print( "tailSet (\"orange\"): printSet( tree.tailSet( "orange" ) ); " ); " ); // get first and last elements System.out.println( "first: " + tree.first() ); System.out.println( "last : " + tree.last() ); } // output set public void printSet( SortedSet set ) { Iterator iterator = set.iterator(); Use TreeSet method headSet to get TreeSet subset less than "orange" Use TreeSet method tailSet to get TreeSet subset greater than "orange" Methods first and last obtain smallest and largest TreeSet elements, respectively 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 } while ( iterator.hasNext() ) System.out.print( iterator.next() + " " ); System.out.println(); } // execute application public static void main( String args[] ) { new SortedSetTest(); } Outline Use Iterator to traverse HashSet and print Fig. values 21.12 Using SortedSets and TreeSets. (Part 2) Lines 37-38 // end class SortedSetTest set: black green grey orange red tan white yellow headSet ("orange"): tailSet ("orange"): first: black last : yellow black green grey orange red tan white 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig. 21.13: MapTest.java // Using a HashMap to store the number of words that // begin with a given letter // Java core packages import java.util.*; public class MapTest { private static String names[] = { "one", "two", "three", "four", "five", "six", "seven", "two", "ten", "four" }; // build a HashMap and output contents public MapTest() { HashMap map = new HashMap(); Integer i; Fig. 21.13 Using HashMaps and Maps. Line 15 Lines 19-20 Create HashMap Lines 25-31 for ( int count = 0; count < names.length; count++ ) { i = ( Integer ) map.get( new Character( names[ count ].charAt( 0 ) ) ); // if key is not in map then give it value one // otherwise increment its value by 1 if ( i == null ) map.put( new Character( names[ count ].charAt( 0 ) ), new Integer( 1 ) ); else map.put( new Character( names[ count ].charAt( 0 ) ), new Integer( i.intValue() + 1 ) ); Use method get to retrieve a Character from HashMap Use method put to store a Character with an Integer key in HashMap } System.out.println( "\nnumber of words beginning with each letter: " ); 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 } printMap( map ); } // output map contents public void printMap( Map mapRef ) { System.out.println( mapRef.toString() ); System.out.println( "size: " + mapRef.size() ); System.out.println( "isEmpty: " + mapRef.isEmpty() ); } Outline Fig. 21.13 Using HashMaps and Maps. (Part 2) // execute application public static void main( String args[] ) { new MapTest(); } // 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 wra 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.