2000 prentice hall, inc. all rights reserved. 1 chapter 24 - collections outline 24.1introduction...

38
2000 Prentice Hall, Inc. All rights reserved. 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

Upload: susanna-riley

Post on 28-Dec-2015

222 views

Category:

Documents


3 download

TRANSCRIPT

2000 Prentice Hall, Inc. All rights reserved.

1

Chapter 24 - Collections

Outline24.1 Introduction24.2 Overview24.3 Class Arrays24.4 Interface Collection and Class Collections24.5 Lists24.6 Algorithms24.6.1 Algorithm sort24.6.2 Algorithm shuffle24.6.3 Algorithms reverse, fill, copy, max and min24.6.4 Algorithm binarySearch24.7 Sets24.8 Maps24.9 Synchronization Wrappers24.10 Unmodifiable Wrappers24.11 Abstract Implementations

2000 Prentice Hall, Inc. All rights reserved.

2

24.1Introduction

• 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

2000 Prentice Hall, Inc. All rights reserved.

3

24.2Overview

• 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

2000 Prentice Hall, Inc. All rights reserved.

4

24.3Class 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

2000 Prentice Hall, Inc. All rights reserved.

5

24.3Class 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

2000 Prentice Hall, Inc. All rights reserved.

Outline6

1. Initialize arrays

1.1 Constructor

1.2 Arrays.fill

1.3 Arrays.sort

2. Method printArrays

1 // Fig. 24.1 : UsingArrays.java2 // Using Java arrays3 import java.util.*;45 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[];910 public UsingArrays()11 {12 filledInt = new int[ 10 ];13 intValuesCopy = new int[ intValues.length ];14 Arrays.fill( filledInt, 7 ); // fill with 7s15 Arrays.sort( doubleValues ); // sort doubleValues16 System.arraycopy( intValues, 0, intValuesCopy,17 0, intValues.length );18 }1920 public void printArrays()21 { 22 System.out.print( "doubleValues: " );23 for ( int k = 0; k < doubleValues.length; k++ )24 System.out.print( doubleValues[ k ] + " " );2526 System.out.print("\nintValues: " );27 for ( int k = 0; k < intValues.length; k++ )28 System.out.print( intValues[ k ] + " " );2930 System.out.print("\nfilledInt: " );

2000 Prentice Hall, Inc. All rights reserved.

Outline7

3. Arrays.binary Search

4. Arrays.equals

5. main

31 for ( int k = 0; k < filledInt.length; k++ )32 System.out.print( filledInt[ k ] + " " );3334 System.out.print("\nintValuesCopy: " );35 for ( int k = 0; k < intValuesCopy.length; k++ )36 System.out.print( intValuesCopy[ k ] + " " );3738 System.out.println();39 }4041 public int searchForInt( int value )42 { 43 return Arrays.binarySearch( intValues, value );44 }4546 public void printEquality()47 {48 boolean b = Arrays.equals( intValues, intValuesCopy );4950 System.out.println( "intValues " + ( b ? "==" : "!=" )51 + " intValuesCopy" );5253 b = Arrays.equals( intValues, filledInt );5455 System.out.println( "intValues " + ( b ? "==" : "!=" )56 + " filledInt" );57 }5859 public static void main( String args[] )60 {

2000 Prentice Hall, Inc. All rights reserved.

Outline8

5. main

Program Output

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 }

doubleValues: 0.2 3.4 7.9 8.4 9.3intValues: 1 2 3 4 5 6filledInt: 7 7 7 7 7 7 7 7 7 7intValuesCopy: 1 2 3 4 5 6intValues == intValuesCopyintValues != filledIntFound 5 at element 4 in intValues8763 not found in intValues

2000 Prentice Hall, Inc. All rights reserved.

9

24.3Class 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

2000 Prentice Hall, Inc. All rights reserved.

Outline10

1. Initialize array

1.1 Constructor

1.2 asList

1.3 set

2. printElements

1 // Fig. 24.2 : UsingAsList.java

2 // Using method asList

3 import java.util.*;

4

5 public class UsingAsList {

6 private String values[] = { "red", "white", "blue" };

7 private List theList;

8

9 public UsingAsList()

10 {

1111 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 }

Create List representation of array. Change the List and the array changes as well.

2000 Prentice Hall, Inc. All rights reserved.

Outline11

3. main

Program Output

27

28 public static void main( String args[] )

29 {

30 new UsingAsList().printElements();

31 }

32 }

List elements : red green blueArray elements: red green blue

2000 Prentice Hall, Inc. All rights reserved.

12

24.4Interface 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.

2000 Prentice Hall, Inc. All rights reserved.

13

24.5Lists

• 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

2000 Prentice Hall, Inc. All rights reserved.

14

24.5Lists

• ArrayList– add( element )– get( index )– size()

• Iterators– Method iterator()

• Returns iterator reference for any Collection

– Iterator methods• hasNext()• next()• remove()

2000 Prentice Hall, Inc. All rights reserved.

Outline15

1. Initialize array

1.1 Constructor

1.2 ArrayList

1.3 Initailize ArrayList

1.4 add

1.5 Call removeStrings

1 // Fig. 24.3 : CollectionTest.java2 // Using the Collection interface3 import java.util.*;4 import java.awt.Color;56 public class CollectionTest {7 private String colors[] = { "red", "white", "blue" };8  9 public CollectionTest()10 {11 ArrayList aList = new ArrayList(); 1213 aList.add( Color.magenta ); // add a color object1415 for ( int k = 0; k < colors.length; k++ )16 aList.add( colors[ k ] ); 1718 aList.add( Color.cyan ); // add a color object1920 System.out.println( "\nArrayList: " );21 for ( int k = 0; k < aList.size(); k++ )22 System.out.print( aList.get( k ) + " " );2324 removeStrings( aList );2526 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 }

2000 Prentice Hall, Inc. All rights reserved.

Outline16

2. Method removeStrings

2.1 iterator

2.2 hastNext

2.3 remove

Program Output

31

3232 public void removeStrings( Collection c )

33 {

34 Iterator i = c.iterator(); // get iterator

35

36 while ( i.hasNext() ) // loop while collection has items

37

3838 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 }

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]

Takes a Collection object and gets iterator.

Remove any Strings from ArrayList.

2000 Prentice Hall, Inc. All rights reserved.

17

24.5Lists

• LinkedList– add( element )– addAll( otherLinkedList )

• Adds all elements

– listIterator()• Return bidirectional iterator

– sublist( begin, end )– clear()

2000 Prentice Hall, Inc. All rights reserved.

Outline18

1. Initialize arrays

1.1 LinkedList

1.2 Initialize LinkedLists

1.3 addAll

1.4 uppercaseStrings

1.5 removeItems

1 // Fig. 24.4 : ListTest.java2 // Using LinkLists3 import java.util.*;45 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

1617 for ( int k = 0; k < colors.length; k++ ) {18 link.add( colors[ k ] );19 link2.add( colors2[ k ] ); // same length as colors20 }2122 link.addAll( link2 ); // concatenate lists23 link2 = null; // release resources2425 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 );

2000 Prentice Hall, Inc. All rights reserved.

Outline19

2. printList

3. uppercaseStrings

3.1 set

4. removeItems

4.1 sublist

4.2 clear

31 }3233 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 ) + " " );3839 System.out.println();40 } 4142 public void uppercaseStrings( List listRef2 )43 {44 ListIterator listIt = listRef2.listIterator();4546 while ( listIt.hasNext() ) {47 Object o = listIt.next(); // get item4849 if ( o instanceof String ) // check for String50 listIt.set( ( ( String ) o ).toUpperCase() ); 51 }52 }5354 public void removeItems( List listRef3, int start, int end )55 {

5656 listRef3.subList( start, end ).clear(); // remove items57 }58 59 public static void main( String args[] )60 {

Notice chained method call.

2000 Prentice Hall, Inc. All rights reserved.

Outline20

Program Output

61 new ListTest();

62 }

63 }

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

2000 Prentice Hall, Inc. All rights reserved.

21

24.5Lists

• Other methods– toArray

• Creates array from a collection

2000 Prentice Hall, Inc. All rights reserved.

22

24.6Algorithms

• 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

2000 Prentice Hall, Inc. All rights reserved.

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

2000 Prentice Hall, Inc. All rights reserved.

Outline24

1. Initialize array

2. printElements

2.1 asList

2.2 sort

1 // Fig. 24.6 : Sort1.java2 // Using algorithm sort3 import java.util.*;45 public class Sort1 {6 private static String suits[] = { "Hearts", "Diamonds",7 "Clubs", "Spades" };89 public void printElements()10 {11 ArrayList theList =1212 new ArrayList( Arrays.asList( suits ) );13 14 System.out.println( "Unsorted array elements:\n" +15 theList );1617 Collections.sort( theList ); // sort the List1819 System.out.println( "Sorted array elements:\n" +20 theList );21 }2223 public static void main( String args[] )24 {25 new Sort1().printElements();26 } 27 }

Unsorted array elements:[Hearts, Diamonds, Clubs, Spades]Sorted array elements:[Clubs, Diamonds, Hearts, Spades]

Converts array to List, used to initialize ArrayList.

2000 Prentice Hall, Inc. All rights reserved.

25

24.6.2 Algorithm shuffle

• shuffle– Randomly order's List's elements– Collections.shuffle( listToShuffle )

2000 Prentice Hall, Inc. All rights reserved.

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 )

2000 Prentice Hall, Inc. All rights reserved.

Outline27

1. Initialize array

1.1 Constructor

1.2 asList

1.3 printStatistics

1.4 reverse

1.5 copy

1.6 fill

1 // Fig. 24.9 : Algorithms1.java2 // Using algorithms reverse, fill, copy, min and max3 import java.util.*;45 public class Algorithms1 {6 private String letters[] = { "P", "C", "M" }, lettersCopy[];7 private List theList, copyList;89 public Algorithms1()10 {11 theList = Arrays.asList( letters ); // get List12 lettersCopy = new String[ 3 ];13 copyList = Arrays.asList( lettersCopy );14 15 System.out.println( "Printing initial statistics: " );16 printStatistics( theList );1718 Collections.reverse( theList ); // reverse order19 System.out.println( "\nPrinting statistics after " +20 "calling reverse: " );21 printStatistics( theList );2223 Collections.copy( copyList, theList ); // copy List24 System.out.println( "\nPrinting statistics after " +25 "copying: " );26 printStatistics( copyList );2728 System.out.println( "\nPrinting statistics after " + 29 "calling fill: " );30 Collections.fill( theList, "R" );

2000 Prentice Hall, Inc. All rights reserved.

Outline28

2. printStatistics

2.1 max

2.2 min

3. main

31 printStatistics( theList );32 }3334 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 ) + " " );3940 System.out.print( "\nMax: " + Collections.max( listRef ) );41 System.out.println( " Min: " + 42 Collections.min( listRef ) );43 }4445 public static void main( String args[] )46 {47 new Algorithms1();48 } 49 }

2000 Prentice Hall, Inc. All rights reserved.

Outline29

Program Output

Printing initial statistics:The list is: P C MMax: P Min: C Printing statistics after calling reverse:The list is: M C PMax: P Min: C Printing statistics after copying:The list is: M C PMax: P Min: C Printing statistics after calling fill:The list is: R R RMax: R Min: R

2000 Prentice Hall, Inc. All rights reserved.

30

24.6.4 Algorithm binarySearch

2000 Prentice Hall, Inc. All rights reserved.

31

24.7Sets

2000 Prentice Hall, Inc. All rights reserved.

32

24.8Maps

2000 Prentice Hall, Inc. All rights reserved.

33

24.9 Synchronization Wrappers

2000 Prentice Hall, Inc. All rights reserved.

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)

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 )

2000 Prentice Hall, Inc. All rights reserved.

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

2000 Prentice Hall, Inc. All rights reserved.

36

2000 Prentice Hall, Inc. All rights reserved.

37

2000 Prentice Hall, Inc. All rights reserved.

38