Java - profthinh ď jhtp5_22 tài liệu, giáo án, bài giảng , luận văn, luận án, đồ án, bài tập lớn về tất cả các lĩnh vực...
Chapter 22 – Collections Outline 22.1 22.2 22.3 22.4 22.5 22.6 22.7 22.8 22.9 22.10 22.11 Introduction Collections Overview Class Arrays Interface Collection and Class Collections Lists Algorithms 22.6.1 Algorithm sort 22.6.2 Algorithm shuffle 22.6.3 Algorithms reverse, fill, copy, max and 22.6.4 Algorithm binarySearch Sets Maps Synchronization Wrappers Unmodifiable Wrappers Abstract Implementations 2003 Prentice Hall, Inc All rights reserved Chapter 22 – Collections Outline 22.12 (Optional) Discovering Design Patterns: Design Patterns Used in Package java.util 22.12.1 Creational Design Patterns 22.12.2 Behavioral Design Patterns 22.12.3 Conclusion 2003 Prentice Hall, Inc All rights reserved 22.1 Introduction • Java collections framework – Provides reusable componentry – Common data structures • Example of code reuse 2003 Prentice Hall, Inc All rights reserved 22.2 Collections Overview • Collection – Data structure (object) that can hold references to other objects • Collections framework – Interfaces declare operations for various collection types – Belong to package java.util • Collection • Set • List • Map 2003 Prentice Hall, Inc All rights reserved 22.3 Class Arrays • Class Arrays – Provides static methods for manipulating arrays – Provides “high-level” methods • Method arrays • Method • Method arrays • Method binarySearch for searching sorted equals for comparing arrays fill for placing values into sort for sorting arrays 2003 Prentice Hall, Inc All rights reserved 5 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Outline // Fig 22.1: UsingArrays.java // Using Java arrays import java.util.*; public class UsingArrays { private int intValues[] = { 1, 2, 3, 4, 5, }; 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 16 Line 18 Lines 21-22 Use static method fill of class Arrays to populate array with 7s Arrays.fill( filledInt, ); // fill with 7s Arrays.sort( doubleValues ); // sort doubleValues ascending // copy array intValues into array intValuesCopy System.arraycopy( intValues, 0, intValuesCopy, 0, intValues.length ); UsingArrays.jav a 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 2003 Prentice Hall, Inc All rights reserved 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // output values in each array public void printArrays() { System.out.print( "doubleValues: " ); for ( int count = 0; count < doubleValues.length; count++ ) System.out.print( doubleValues[ count ] + " " ); Outline UsingArrays.jav a System.out.print( "\nintValues: " ); for ( int count = 0; count < intValues.length; count++ ) System.out.print( intValues[ count ] + " " ); System.out.print( "\nfilledInt: " ); for ( int count = 0; count < filledInt.length; count++ ) System.out.print( filledInt[ count ] + " " ); System.out.print( "\nintValuesCopy: " ); for ( int count = 0; count < intValuesCopy.length; count++ ) System.out.print( intValuesCopy[ count ] + " " ); System.out.println(); } // end method printArrays 2003 Prentice Hall, Inc All rights reserved 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 // find value in array intValues public int searchForInt( int value ) { return Arrays.binarySearch( intValues, value ); } // compare array contents public void printEquality() { boolean b = Arrays.equals( intValues, intValuesCopy ); System.out.println( "intValues " + ( b ? "==" : "!=" ) + " intValuesCopy" ); b = Arrays.equals( intValues, filledInt ); Outline Use static method UsingArrays.jav binarySearch of class Arrays a search on array to perform binary Line 55 Lines 61 and 66 Use static method equals of class Arrays to determine whether values of the two arrays are equivalent System.out.println( "intValues " + ( b ? "==" : "!=" ) + " filledInt" ); } 2003 Prentice Hall, Inc All rights reserved 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 public static void main( String args[] ) { UsingArrays usingArrays = new UsingArrays(); usingArrays.printArrays(); usingArrays.printEquality(); Outline UsingArrays.jav a int location = usingArrays.searchForInt( ); System.out.println( ( location >= ? "Found at element " + location : "5 not found" ) + " in intValues" ); location = usingArrays.searchForInt( 8763 ); System.out.println( ( location >= ? "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: filledInt: 7 7 7 7 7 intValuesCopy: intValues == intValuesCopy intValues != filledInt Found at element in intValues 8763 not found in intValues 2003 Prentice Hall, Inc All rights reserved 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Outline // Fig 22.2: UsingAsList.java // Using method asList import java.util.*; public class UsingAsList { private static final String values[] = { "red", "white", "blue" }; private List list; // initialize List and set value at location 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: " ); UsingAsList.jav a Line 12 Use static method asList Line 13 to return of class Arrays List view of array values Line 21 Use method set of List Line 22 object to change the contents of element to "green" List method size returns number of elements in List List method get returns individual element in List 2003 Prentice Hall, Inc All rights reserved 49 22.8 Maps • Map – Associates keys to values – Cannot contain duplicate keys • Called one-to-one mapping 2003 Prentice Hall, Inc All rights reserved 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig 21.14: WordTypeCount.java // Program counts the number of occurrences of each word in a string import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; Outline MapTest.java Line 21 public class WordTypeCount extends JFrame { private JTextArea inputField; private JLabel prompt; private JTextArea display; private JButton goButton; private Map map; public WordTypeCount() { super( "Word Type Count" ); inputField = new JTextArea( 3, 20 ); map = new HashMap(); Create HashMap goButton = new JButton( "Go" ); goButton.addActionListener( 2003 Prentice Hall, Inc All rights reserved 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 new ActionListener() { // inner class public void actionPerformed( ActionEvent event ) { createMap(); display.setText( createOutput() ); } Outline MapTest.java } // end inner class ); // end call to addActionListener prompt = new JLabel( "Enter a string:" ); display = new JTextArea( 15, 20 ); display.setEditable( false ); JScrollPane displayScrollPane = new JScrollPane( display ); // add components to GUI Container container = getContentPane(); container.setLayout( new FlowLayout() ); container.add( prompt ); container.add( inputField ); container.add( goButton ); container.add( displayScrollPane ); 2003 Prentice Hall, Inc All rights reserved 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 Outline setSize( 400, 400 ); show(); } // end constructor MapTest.java // create map from user input private void createMap() { String input = inputField.getText(); StringTokenizer tokenizer = new StringTokenizer( input ); Line 69 Lines 72 and 75 while ( tokenizer.hasMoreTokens() ) { String word = tokenizer.nextToken().toLowerCase(); // get word // if the map contains the word if ( map.containsKey( word ) ) { Use method get to retrieve a Character from HashMap Integer count = (Integer) map.get( word ); // get value // increment value map.put( word, new Integer( count.intValue() + ) ); Use method put to store a } else // otherwise add word with a value of to map Character with an map.put( word, new Integer( ) ); Integer key in HashMap } // end while } // end method createMap 2003 Prentice Hall, Inc All rights reserved 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 // create string containing map values private String createOutput() { StringBuffer output = new StringBuffer( "" ); Iterator keys = map.keySet().iterator(); Outline MapTest.java // iterate through the keys while ( keys.hasNext() ) { Object currentKey = keys.next(); // output the key-value pairs output.append( currentKey + "\t" + map.get( currentKey ) + "\n" ); } output.append( "size: " + map.size() + "\n" ); output.append( "isEmpty: " + map.isEmpty() + "\n" ); return output.toString(); } // end method createOutput 2003 Prentice Hall, Inc All rights reserved 102 public static void main( String args[] ) 103 { 104 WordTypeCount application = new WordTypeCount(); 105 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 106 } 107 108 } // end class WordTypeCount Outline MapTest.java 2003 Prentice Hall, Inc All rights reserved 55 22.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 2003 Prentice Hall, Inc All rights reserved 22.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 22.15 Synchronization wrapper methods 2003 Prentice Hall, Inc All rights reserved 56 57 22.10 Unmodifiable Wrappers • Unmodifiable wrappers – Converting collections to unmodifiable collections – Throw UnsorrtedOperationException if attempts are made to modify the collection 2003 Prentice Hall, Inc All rights reserved 58 22.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 22.16 Unmodifiable wrapper methods 2003 Prentice Hall, Inc All rights reserved 59 22.11 Abstract Implementations • Abstract implementations – Offer “bare bones” implementation of collection interfaces • Programmers can “flesh out” customizable implementations – – – – – AbstractCollection AbstractList AbstractMap AbstractSequentialList AbstractSet 2003 Prentice Hall, Inc All rights reserved 22.12 (Optional) Discovering Design Patterns: Design Patterns Used in Package java.util • Design patterns in package java.util 2003 Prentice Hall, Inc All rights reserved 60 61 22.12.1 Creational Design Patterns • Prototype 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 2003 Prentice Hall, Inc All rights reserved 62 22.12.2 Behavioral Design Patterns • 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 2003 Prentice Hall, Inc All rights reserved 63 22.12.3 Conclusion • Design patterns described by the “Gang of Four” – Creational – Structural – Behavioral • Design patterns not described by the “Gang of Four” – Concurrency patterns – Architectural patterns 2003 Prentice Hall, Inc All rights reserved ... CollectionTest java 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]... 24 25 26 27 Outline // Fig 22.3: CollectionTest .java // Using the Collection interface import java. awt.Color; import java. util.*; CollectionTest java public class CollectionTest { private static... 5 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Outline // Fig 22.1: UsingArrays .java // Using Java arrays import java. util.*; public class UsingArrays { private int intValues[] = { 1, 2, 3, 4,