1 / 38

Chapter 24 - Collections

Chapter 24 - Collections. Outline 24.1 Introduction 24.2 Overview 24.3 Class Arrays 24.4 Interface Collection and Class Collections 24.5 Lists 24.6 Algorithms 24.6.1 Algorithm sort 24.6.2 Algorithm shuffle 24.6.3 Algorithms reverse , fill , copy , max and min

Download Presentation

Chapter 24 - Collections

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 24 - Collections Outline 24.1 Introduction 24.2 Overview 24.3 Class Arrays 24.4 Interface Collection and Class Collections 24.5 Lists 24.6 Algorithms 24.6.1 Algorithm sort 24.6.2 Algorithm shuffle 24.6.3 Algorithms reverse, fill, copy, max and min 24.6.4 Algorithm binarySearch 24.7 Sets 24.8 Maps 24.9 Synchronization Wrappers 24.10 Unmodifiable Wrappers 24.11 Abstract Implementations

  2. 24.1 Introduction • Java collections framework • Package java.util • Prepackaged data structures • Algorithms • Code reuse • Create structures from existing ones • No need to know implementation • Reuable components • Standardized • Easy to share • Rapid execution, efficient memory use

  3. 24.2 Overview • Collection • Data structure (object) that can hold other objects • Collection interface • Define operations that can be used • Collection implementation • Implement interface operations • Carefully constructed for efficiency and speed • Interfaces • Some interfaces define generic operations for collections • Set, List, Map

  4. 24.3 Class Arrays • Class Arrays • static methods for manipulating arrays • Has "high-level" methods • fill( arrayToFill, value ) • Sets all elements of arrayToFill to value • sort( arrayToSort ) • Ascending order • arrayCopy( sourceArray, startIndex, receivingArray, receiveIndex, number ) • Copies number elements into receivingArray, beginning at location receiveIndex • Copies from startIndex in sourceArray

  5. 24.3 Class Arrays • Class Arrays • binarySearch( arrayToSearch, value ) • Use with sorted array • Searches for value, returns index • If not found, returns index it should be at, minus 1 • Returns -7 if should be at index 6 • equals( array1, array2 ) • Returns true if equal

  6. 1 // Fig. 24.1 : UsingArrays.java 2 // Using Java arrays 3 import java.util.*; 4 5 public class UsingArrays { 6 private int intValues[] = { 1, 2, 3, 4, 5, 6 }; 7 private double doubleValues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; 8 private int filledInt[], intValuesCopy[]; 9 10 public UsingArrays() 11 { 12 filledInt = new int[ 10 ]; 13 intValuesCopy = new int[ intValues.length ]; 14 Arrays.fill( filledInt, 7 ); // fill with 7s 15 Arrays.sort( doubleValues ); // sort doubleValues 16 System.arraycopy( intValues, 0, intValuesCopy, 17 0, intValues.length ); 18 } 19 20 public void printArrays() 21 { 22 System.out.print( "doubleValues: " ); 23 for ( int k = 0; k < doubleValues.length; k++ ) 24 System.out.print( doubleValues[ k ] + " " ); 25 26 System.out.print("\nintValues: " ); 27 for ( int k = 0; k < intValues.length; k++ ) 28 System.out.print( intValues[ k ] + " " ); 29 30 System.out.print("\nfilledInt: " ); 1. Initialize arrays 1.1 Constructor 1.2 Arrays.fill 1.3 Arrays.sort 2. Method printArrays

  7. 31 for ( int k = 0; k < filledInt.length; k++ ) 32 System.out.print( filledInt[ k ] + " " ); 33 34 System.out.print("\nintValuesCopy: " ); 35 for ( int k = 0; k < intValuesCopy.length; k++ ) 36 System.out.print( intValuesCopy[ k ] + " " ); 37 38 System.out.println(); 39 } 40 41 public int searchForInt( int value ) 42 { 43 return Arrays.binarySearch( intValues, value ); 44 } 45 46 public void printEquality() 47 { 48 boolean b = Arrays.equals( intValues, intValuesCopy ); 49 50 System.out.println( "intValues " + ( b ? "==" : "!=" ) 51 + " intValuesCopy" ); 52 53 b = Arrays.equals( intValues, filledInt ); 54 55 System.out.println( "intValues " + ( b ? "==" : "!=" ) 56 + " filledInt" ); 57 } 58 59 public static void main( String args[] ) 60 { 3. Arrays.binary Search 4. Arrays.equals 5. main

  8. 61 UsingArrays u = new UsingArrays(); 62 63 u.printArrays(); 64 u.printEquality(); 65 66 int n = u.searchForInt( 5 ); 67 System.out.println( ( n >= 0 ? "Found 5 at element " + n : 68 "5 not found" ) + " in intValues" ); 69 n = u.searchForInt( 8763 ); 70 System.out.println( ( n >= 0 ? "Found 8763 at element " 71 + n : "8763 not found" ) 72 + " in intValues" ); 73 } 74 } 5. main Program Output 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

  9. 24.3 Class Arrays • Views • Manipulate one collection as if it were of another type • View is public set of methods • asList( array ) • Returns fixed-size List (similar to linked list, more later) • Can manipulate array using the List view • Any modifications to List or array change the other as well • set( index, value ) (List method) • Sets element to value • size() • get( index ) • Returns value

  10. 1 // Fig. 24.2 : UsingAsList.java 2 // Using method asList 3 import java.util.*; Create List representation of array. Change the List and the array changes as well. 4 5 public class UsingAsList { 6 private String values[] = { "red", "white", "blue" }; 7 private List theList; 8 9 public UsingAsList() 10 { 11 theList = Arrays.asList( values ); // get List 12 theList.set( 1, "green" ); // change a value 13 } 14 15 public void printElements() 16 { 17 System.out.print( "List elements : " ); 18 for ( int k = 0; k < theList.size(); k++ ) 19 System.out.print( theList.get( k ) + " " ); 20 21 System.out.print( "\nArray elements: " ); 22 for ( int k = 0; k < values.length; k++ ) 23 System.out.print( values[ k ] + " " ); 24 25 System.out.println(); 26 } 1. Initialize array 1.1 Constructor 1.2 asList 1.3 set 2. printElements

  11. 27 28 public static void main( String args[] ) 29 { 30 new UsingAsList().printElements(); 31 } 32 } 3. main Program Output List elements : red green blue Array elements: red green blue

  12. 24.4 Interface Collection and Class Collections • Interface Collection • Root interface in collections hierarchy • Superclass of Set and List • Bulk operations (performed on entire collection) • Adding, clearing, comparing, retaining elements • Can get an Iterator • Similar to Enumerations, but can remove elements • Can determine size, hash code, if empty • Class Collections • Has static methods to manipulate collections polymorphically • Searching, sorting, etc.

  13. 24.5 Lists • List (sequence) • Ordered Collection • Can contain duplicate elements • Can manipulate elements using indeces, range of elements, getting a ListIterator • Interface List implemented by • ArrayList - resizable-array, similar to Vector • LinkedList - linked list • Vector

  14. 24.5 Lists • ArrayList • add( element ) • get( index ) • size() • Iterators • Method iterator() • Returns iterator reference for any Collection • Iterator methods • hasNext() • next() • remove()

  15. 1 // Fig. 24.3 : CollectionTest.java 2 // Using the Collection interface 3 import java.util.*; 4 import java.awt.Color; 5 6 public class CollectionTest { 7 private String colors[] = { "red", "white", "blue" }; 8 9 public CollectionTest() 10 { 11 ArrayList aList = new ArrayList(); 12 13 aList.add( Color.magenta ); // add a color object 14 15 for ( int k = 0; k < colors.length; k++ ) 16 aList.add( colors[ k ] ); 17 18 aList.add( Color.cyan ); // add a color object 19 20 System.out.println( "\nArrayList: " ); 21 for ( int k = 0; k < aList.size(); k++ ) 22 System.out.print( aList.get( k ) + " " ); 23 24 removeStrings( aList ); 25 26 System.out.println( "\n\nArrayList after calling" + 27 " removeStrings: " ); 28 for ( int k = 0; k < aList.size(); k++ ) 29 System.out.print( aList.get( k ) + " " ); 30 } 1. Initialize array 1.1 Constructor 1.2 ArrayList 1.3 Initailize ArrayList 1.4 add 1.5 Call removeStrings

  16. 31 Takes a Collection object and gets iterator. 32 public void removeStrings( Collection c ) 33 { 34 Iterator i = c.iterator(); // get iterator Remove any Strings from ArrayList. 35 36 while ( i.hasNext() ) // loop while collection has items 37 38 if ( i.next() instanceof String ) 39 i.remove(); // remove String object 40 } 41 42 public static void main( String args[] ) 43 { 44 new CollectionTest(); 45 } 46 } 2. Method removeStrings 2.1 iterator 2.2 hastNext 2.3 remove Program Output 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]

  17. 24.5 Lists • LinkedList • add( element ) • addAll( otherLinkedList ) • Adds all elements • listIterator() • Return bidirectional iterator • sublist( begin, end ) • clear()

  18. 1 // Fig. 24.4 : ListTest.java 2 // Using LinkLists 3 import java.util.*; 4 5 public class ListTest { 6 private String colors[] = { "black", "yellow", "green", 7 "blue", "violet", "silver" }; 8 private String colors2[] = { "gold", "white", "brown", 9 "blue", "gray", "silver" }; 10 11 public ListTest() 12 { 13 LinkedList link = new LinkedList(); 14 LinkedList link2 = new LinkedList(); 15 16 17 for ( int k = 0; k < colors.length; k++ ) { 18 link.add( colors[ k ] ); 19 link2.add( colors2[ k ] ); // same length as colors 20 } 21 22 link.addAll( link2 ); // concatenate lists 23 link2 = null; // release resources 24 25 printList( link ); 26 uppercaseStrings( link ); 27 printList( link ); 28 System.out.print( "\nDeleting elements 4 to 6..." ); 29 removeItems( link, 4, 7 ); 30 printList( link ); 1. Initialize arrays 1.1 LinkedList 1.2 Initialize LinkedLists 1.3 addAll 1.4 uppercaseStrings 1.5 removeItems

  19. 31 } 32 33 public void printList( List listRef ) 34 { 35 System.out.println( "\nlist: " ); 36 for ( int k = 0; k < listRef.size(); k++ ) 37 System.out.print( listRef.get( k ) + " " ); 38 Notice chained method call. 39 System.out.println(); 40 } 41 42 public void uppercaseStrings( List listRef2 ) 43 { 44 ListIterator listIt = listRef2.listIterator(); 45 46 while ( listIt.hasNext() ) { 47 Object o = listIt.next(); // get item 48 49 if ( o instanceof String ) // check for String 50 listIt.set( ( ( String ) o ).toUpperCase() ); 51 } 52 } 53 54 public void removeItems( List listRef3, int start, int end ) 55 { 56 listRef3.subList( start, end ).clear(); // remove items 57 } 58 59 public static void main( String args[] ) 60 { 2. printList 3. uppercaseStrings 3.1 set 4. removeItems 4.1 sublist 4.2 clear

  20. 61 new ListTest(); 62 } 63 } Program Output 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

  21. 24.5 Lists • Other methods • toArray • Creates array from a collection

  22. 24.6 Algorithms • Collections framework • Has high-performance algorithms for manipulating collection elements • static methods • List algorithms • sort, binarySearch, reverse, shuffle, fill, copy • Collections algorithms • min and max

  23. 24.6.1 Algorithm sort • sort • Sorts elements of List • Order determined by element's type • Fast sorting • Runs in n log(n) time • Sorting order • Use a Comparator object • Method reverseOrder returns a Comparator object • sort( myList, Collections.reverseOrder() )

  24. 1 // Fig. 24.6 : Sort1.java 2 // Using algorithm sort 3 import java.util.*; Converts array to List, used to initialize ArrayList. 4 5 public class Sort1 { 6 private static String suits[] = { "Hearts", "Diamonds", 7 "Clubs", "Spades" }; 8 9 public void printElements() 10 { 11 ArrayList theList = 12 new ArrayList( Arrays.asList( suits ) ); 13 14 System.out.println( "Unsorted array elements:\n" + 15 theList ); 16 17 Collections.sort( theList ); // sort the List 18 19 System.out.println( "Sorted array elements:\n" + 20 theList ); 21 } 22 23 public static void main( String args[] ) 24 { 25 new Sort1().printElements(); 26 } 27 } 1. Initialize array 2. printElements 2.1 asList 2.2 sort Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted array elements: [Clubs, Diamonds, Hearts, Spades]

  25. 24.6.2 Algorithm shuffle • shuffle • Randomly order's List's elements • Collections.shuffle( listToShuffle )

  26. 24.6.3 Algorithms reverse, fill, copy, max and min • Algorithms for Lists • reverse( listToReverse ) • Reverse order of elements • fill(listToFill, value) • Overwrites elements with value • copy( destinationList, sourceList ) • Copies all elements • Destination must have enough elements • Algorithms for Collections • static methods max and min • Collections.min( collectionsRef )

  27. 1 // Fig. 24.9 : Algorithms1.java 2 // Using algorithms reverse, fill, copy, min and max 3 import java.util.*; 4 5 public class Algorithms1 { 6 private String letters[] = { "P", "C", "M" }, lettersCopy[]; 7 private List theList, copyList; 8 9 public Algorithms1() 10 { 11 theList = Arrays.asList( letters ); // get List 12 lettersCopy = new String[ 3 ]; 13 copyList = Arrays.asList( lettersCopy ); 14 15 System.out.println( "Printing initial statistics: " ); 16 printStatistics( theList ); 17 18 Collections.reverse( theList ); // reverse order 19 System.out.println( "\nPrinting statistics after " + 20 "calling reverse: " ); 21 printStatistics( theList ); 22 23 Collections.copy( copyList, theList ); // copy List 24 System.out.println( "\nPrinting statistics after " + 25 "copying: " ); 26 printStatistics( copyList ); 27 28 System.out.println( "\nPrinting statistics after " + 29 "calling fill: " ); 30 Collections.fill( theList, "R" ); 1. Initialize array 1.1 Constructor 1.2 asList 1.3 printStatistics 1.4 reverse 1.5 copy 1.6 fill

  28. 31 printStatistics( theList ); 32 } 33 34 private void printStatistics( List listRef ) 35 { 36 System.out.print( "The list is: " ); 37 for ( int k = 0; k < listRef.size(); k++ ) 38 System.out.print( listRef.get( k ) + " " ); 39 40 System.out.print( "\nMax: " + Collections.max( listRef ) ); 41 System.out.println( " Min: " + 42 Collections.min( listRef ) ); 43 } 44 45 public static void main( String args[] ) 46 { 47 new Algorithms1(); 48 } 49 } 2. printStatistics 2.1 max 2.2 min 3. main

  29. 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 Program Output

  30. 24.6.4 Algorithm binarySearch

  31. 24.7 Sets

  32. 24.8 Maps

  33. 24.9 Synchronization Wrappers

  34. 24.10 Unmodifiable Wrappers • Collections API • Set of public static methods to convert collections to unmodifiable versions • Unmodifiable wrappers • Throw UnsupportedOperationExceptions • Can give others read-only access (reference to unmodifiable wrapper)

  35. 24.11 Abstract Implementations • Abstract implementation • "Bare bones" implementations of collection interfaces • Programmer quickly fleshes out • AbstractCollection • Thin Collection implementation • AbstractList • Thin List implementation, random-access backing • AbstractMap, AbstractSequentialList, AbstractSet • To write • Select base class implementation • Implement abstract methods • Override concrete methods that prevent modification

More Related