collections - osu.czhunka/vyuka/progobj/oop_8/java_8.pdf · 3 8.1 introduction • java collections...
TRANSCRIPT
1
CollectionsOutline
8.1 Introduction8.2 Collections Overview8.3 Class Arrays8.4 Interface Collection and Class Collections8.5 Lists8.6 Algorithms
8.6.1 Algorithm sort8.6.2 Algorithm shuffle8.6.3 Algorithms reverse, fill, copy, max and min8.6.4 Algorithm binarySearch
8.7 Sets8.8 Maps8.9 Synchronization Wrappers8.10 Unmodifiable Wrappers8.11 Abstract Implementations
2
CollectionsOutline
8.12 (Optional) Discovering Design Patterns: Design Patterns Used in Package java.util8.12.1 Creational Design Patterns8.12.2 Behavioral Design Patterns8.12.3 Conclusion
3
8.1 Introduction
• Java collections framework– Provides reusable componentry
– Common data structures• Example of code reuse
4
8.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
5
8.3 Class ArraysArraysArraysArrays
• 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
Outline
UsingArrays.java
Line 16
Line 18
Lines 21-22
12 // Using Java arrays.// Using Java arrays.// Using Java arrays.// Using Java arrays.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass UsingArraysUsingArraysUsingArraysUsingArrays {{{{
6 privateprivateprivateprivate intintintint intValuesintValuesintValuesintValues[] = { [] = { [] = { [] = { 1111, , , , 2222, , , , 3333, , , , 4444, , , , 5555, , , , 6666 };};};};
7 privateprivateprivateprivate doubledoubledoubledouble doubleValuesdoubleValuesdoubleValuesdoubleValues[] = { [] = { [] = { [] = { 8.48.48.48.4, , , , 9.39.39.39.3, , , , 0.20.20.20.2, , , , 7.97.97.97.9, , , , 3.43.43.43.4 };};};};
8 privateprivateprivateprivate intintintint filledIntfilledIntfilledIntfilledInt[], [], [], [], intValuesCopyintValuesCopyintValuesCopyintValuesCopy[];[];[];[];
9 10 // initialize arrays// initialize arrays// initialize arrays// initialize arrays
11 publicpublicpublicpublic UsingArraysUsingArraysUsingArraysUsingArrays()()()()
12 {{{{
13 filledIntfilledIntfilledIntfilledInt = = = = newnewnewnew intintintint[ [ [ [ 10101010 ];];];];
14 intValuesCopyintValuesCopyintValuesCopyintValuesCopy = = = = newnewnewnew intintintint[ [ [ [ intValues.lengthintValues.lengthintValues.lengthintValues.length ];];];];
15 16 Arrays.fill( Arrays.fill( Arrays.fill( Arrays.fill( filledIntfilledIntfilledIntfilledInt, , , , 7777 ); ); ); ); // fill with 7s// fill with 7s// fill with 7s// fill with 7s
17 18 Arrays.sort( Arrays.sort( Arrays.sort( Arrays.sort( doubleValuesdoubleValuesdoubleValuesdoubleValues ); ); ); ); // sort // sort // sort // sort doubleValuesdoubleValuesdoubleValuesdoubleValues ascendingascendingascendingascending
19 20 // copy array // copy array // copy array // copy array intValuesintValuesintValuesintValues into array into array into array into array intValuesCopyintValuesCopyintValuesCopyintValuesCopy
21 System.arraycopySystem.arraycopySystem.arraycopySystem.arraycopy( ( ( ( intValuesintValuesintValuesintValues, , , , 0000, , , , intValuesCopyintValuesCopyintValuesCopyintValuesCopy, , , ,
22 0000, , , , intValues.lengthintValues.lengthintValues.lengthintValues.length ); ); ); );
23 }}}}
24
Outline
UsingArrays.java
25 // output values in each array// output values in each array// output values in each array// output values in each array
26 publicpublicpublicpublic voidvoidvoidvoid printArraysprintArraysprintArraysprintArrays()()()()
27 { { { {
28 System.out.print( System.out.print( System.out.print( System.out.print( """"doubleValuesdoubleValuesdoubleValuesdoubleValues: ": ": ": " ););););
29 30 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < ; count < ; count < ; count < doubleValues.lengthdoubleValues.lengthdoubleValues.lengthdoubleValues.length; count++ ); count++ ); count++ ); count++ )
31 System.out.print( System.out.print( System.out.print( System.out.print( doubleValuesdoubleValuesdoubleValuesdoubleValues[ count ] + [ count ] + [ count ] + [ count ] + " "" "" "" " ););););
32 33 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nintValuesnintValuesnintValuesnintValues: ": ": ": " ););););
34 35 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < ; count < ; count < ; count < intValues.lengthintValues.lengthintValues.lengthintValues.length; count++ ); count++ ); count++ ); count++ )
36 System.out.print( System.out.print( System.out.print( System.out.print( intValuesintValuesintValuesintValues[ count ] + [ count ] + [ count ] + [ count ] + " "" "" "" " ););););
37 38 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nfilledIntnfilledIntnfilledIntnfilledInt: ": ": ": " ););););
39 40 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < ; count < ; count < ; count < filledInt.lengthfilledInt.lengthfilledInt.lengthfilledInt.length; count++ ); count++ ); count++ ); count++ )
41 System.out.print( System.out.print( System.out.print( System.out.print( filledIntfilledIntfilledIntfilledInt[ count ] + [ count ] + [ count ] + [ count ] + " "" "" "" " ););););
42 43 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nintValuesCopynintValuesCopynintValuesCopynintValuesCopy: ": ": ": " ););););
44 45 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < ; count < ; count < ; count < intValuesCopy.lengthintValuesCopy.lengthintValuesCopy.lengthintValuesCopy.length; count++ ); count++ ); count++ ); count++ )
46 System.out.print( System.out.print( System.out.print( System.out.print( intValuesCopyintValuesCopyintValuesCopyintValuesCopy[ count ] + [ count ] + [ count ] + [ count ] + " "" "" "" " ););););
47 48 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println();();();();
49 50 } } } } // end method // end method // end method // end method printArraysprintArraysprintArraysprintArrays
51
Outline
UsingArrays.java
Line 55
Lines 61 and 66
52 // find value in array // find value in array // find value in array // find value in array intValuesintValuesintValuesintValues
53 publicpublicpublicpublic intintintint searchForIntsearchForIntsearchForIntsearchForInt( ( ( ( intintintint value )value )value )value )
54 { { { {
55 returnreturnreturnreturn Arrays.binarySearchArrays.binarySearchArrays.binarySearchArrays.binarySearch( ( ( ( intValuesintValuesintValuesintValues, value );, value );, value );, value );
56 }}}}
57 58 // compare array contents// compare array contents// compare array contents// compare array contents
59 publicpublicpublicpublic voidvoidvoidvoid printEqualityprintEqualityprintEqualityprintEquality()()()()
60 {{{{
61 booleanbooleanbooleanboolean b = Arrays.equals( b = Arrays.equals( b = Arrays.equals( b = Arrays.equals( intValuesintValuesintValuesintValues, , , , intValuesCopyintValuesCopyintValuesCopyintValuesCopy ););););
62 63 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"intValuesintValuesintValuesintValues """" + ( b ? + ( b ? + ( b ? + ( b ? "==""==""==""==" : : : : "!=""!=""!=""!=" ) +) +) +) +
64 " " " " intValuesCopyintValuesCopyintValuesCopyintValuesCopy"""" ););););
65 66 b = Arrays.equals( b = Arrays.equals( b = Arrays.equals( b = Arrays.equals( intValuesintValuesintValuesintValues, , , , filledIntfilledIntfilledIntfilledInt ););););
67 68 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"intValuesintValuesintValuesintValues """" + ( b ? + ( b ? + ( b ? + ( b ? "==""==""==""==" : : : : "!=""!=""!=""!=" ) +) +) +) +
69 " " " " filledIntfilledIntfilledIntfilledInt"""" ););););
70 }}}}
71
Outline
UsingArrays.java
72 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
73 {{{{
74 UsingArraysUsingArraysUsingArraysUsingArrays usingArraysusingArraysusingArraysusingArrays = = = = newnewnewnew UsingArraysUsingArraysUsingArraysUsingArrays();();();();
75 76 usingArrays.printArraysusingArrays.printArraysusingArrays.printArraysusingArrays.printArrays();();();();
77 usingArrays.printEqualityusingArrays.printEqualityusingArrays.printEqualityusingArrays.printEquality();();();();
78 79 intintintint location = location = location = location = usingArrays.searchForIntusingArrays.searchForIntusingArrays.searchForIntusingArrays.searchForInt( ( ( ( 5555 ););););
80 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( location >= ( ( location >= ( ( location >= ( ( location >= 0000 ? ? ? ? "Found 5 at element ""Found 5 at element ""Found 5 at element ""Found 5 at element " + + + +
81 location : location : location : location : "5 not found""5 not found""5 not found""5 not found" ) + ) + ) + ) + " in " in " in " in intValuesintValuesintValuesintValues"""" ););););
82 83 location = location = location = location = usingArrays.searchForIntusingArrays.searchForIntusingArrays.searchForIntusingArrays.searchForInt( ( ( ( 8763876387638763 ););););
84 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( location >= ( ( location >= ( ( location >= ( ( location >= 0000 ? ? ? ? "Found 8763 at element ""Found 8763 at element ""Found 8763 at element ""Found 8763 at element " + + + +
85 location : location : location : location : "8763 not found""8763 not found""8763 not found""8763 not found" ) + ) + ) + ) + " in " in " in " in intValuesintValuesintValuesintValues"""" ); ); ); );
86 } } } }
87 88 } } } } // end class // end class // end class // end class UsingArraysUsingArraysUsingArraysUsingArrays
doubleValuesdoubleValuesdoubleValuesdoubleValues: 0.2 3.4 7.9 8.4 9.3: 0.2 3.4 7.9 8.4 9.3: 0.2 3.4 7.9 8.4 9.3: 0.2 3.4 7.9 8.4 9.3intValuesintValuesintValuesintValues: 1 2 3 4 5 6: 1 2 3 4 5 6: 1 2 3 4 5 6: 1 2 3 4 5 6filledIntfilledIntfilledIntfilledInt: 7 7 7 7 7 7 7 7 7 7: 7 7 7 7 7 7 7 7 7 7: 7 7 7 7 7 7 7 7 7 7: 7 7 7 7 7 7 7 7 7 7intValuesCopyintValuesCopyintValuesCopyintValuesCopy: 1 2 3 4 5 6: 1 2 3 4 5 6: 1 2 3 4 5 6: 1 2 3 4 5 6intValuesintValuesintValuesintValues == == == == intValuesCopyintValuesCopyintValuesCopyintValuesCopyintValuesintValuesintValuesintValues != != != != filledIntfilledIntfilledIntfilledIntFound 5 at element 4 in Found 5 at element 4 in Found 5 at element 4 in Found 5 at element 4 in intValuesintValuesintValuesintValues8763 not found in 8763 not found in 8763 not found in 8763 not found in intValuesintValuesintValuesintValues
Outline
UsingAsList.java
Line 12
Line 13
Line 21
Line 22
12 // Using method // Using method // Using method // Using method asListasListasListasList....
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass UsingAsListUsingAsListUsingAsListUsingAsList {{{{
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String values[] = { String values[] = { String values[] = { String values[] = { "red""red""red""red", , , , "white""white""white""white", , , , "blue""blue""blue""blue" };};};};
7 privateprivateprivateprivate List list;List list;List list;List list;
8 9 // initialize List and set value at location 1// initialize List and set value at location 1// initialize List and set value at location 1// initialize List and set value at location 1
10 publicpublicpublicpublic UsingAsListUsingAsListUsingAsListUsingAsList()()()()
11 {{{{
12 list = list = list = list = Arrays.asListArrays.asListArrays.asListArrays.asList( values ); ( values ); ( values ); ( values ); // get List // get List // get List // get List
13 list.set( list.set( list.set( list.set( 1111, , , , "green""green""green""green" ); ); ); ); // change a value// change a value// change a value// change a value
14 }}}}
15 16 // output List and array// output List and array// output List and array// output List and array
17 publicpublicpublicpublic voidvoidvoidvoid printElementsprintElementsprintElementsprintElements()()()()
18 {{{{
19 System.out.print( System.out.print( System.out.print( System.out.print( "List elements : ""List elements : ""List elements : ""List elements : " ););););
20 21 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ )
22 System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + " "" "" "" " ););););
23 24 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nArraynArraynArraynArray elements: "elements: "elements: "elements: " ););););
25
Outline
UsingAsList.java
26 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < values.length; count++ ); count < values.length; count++ ); count < values.length; count++ ); count < values.length; count++ )
27 System.out.print( values[ count ] + System.out.print( values[ count ] + System.out.print( values[ count ] + System.out.print( values[ count ] + " "" "" "" " ););););
28 29 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println();();();();
30 }}}}
31 32 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
33 {{{{
34 newnewnewnew UsingAsList().printElementsUsingAsList().printElementsUsingAsList().printElementsUsingAsList().printElements();();();();
35 } } } }
36 37 } } } } // end class // end class // end class // end class UsingAsListUsingAsListUsingAsListUsingAsList
List elements : red green blueList elements : red green blueList elements : red green blueList elements : red green blueArray elements: red green blueArray elements: red green blueArray elements: red green blueArray elements: red green blue
128.4 Interface CollectionCollectionCollectionCollection and ClassCollectionsCollectionsCollectionsCollections
• 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
13
8.5 Lists
• List– Ordered Collection that can contain duplicate elements
– Sometimes called a sequence
– Implemented via interface List
• ArrayList
• LinkedList
• Vector
Outline
CollectionTest.java
Lines 15-20
Line 26
12 // Using the Collection interface.// Using the Collection interface.// Using the Collection interface.// Using the Collection interface.
3 importimportimportimport java.awt.Colorjava.awt.Colorjava.awt.Colorjava.awt.Color;;;;
4 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
5 6 publicpublicpublicpublic classclassclassclass CollectionTestCollectionTestCollectionTestCollectionTest {{{{
7 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String colors[] = { String colors[] = { String colors[] = { String colors[] = { "red""red""red""red", , , , "white""white""white""white", , , , "blue""blue""blue""blue" };};};};
8 9 // create // create // create // create ArrayListArrayListArrayListArrayList, add objects to it and manipulate it, add objects to it and manipulate it, add objects to it and manipulate it, add objects to it and manipulate it
10 publicpublicpublicpublic CollectionTestCollectionTestCollectionTestCollectionTest()()()()
11 {{{{
12 List list = List list = List list = List list = newnewnewnew ArrayListArrayListArrayListArrayList(); (); (); ();
13 14 // add objects to list// add objects to list// add objects to list// add objects to list
15 list.add( list.add( list.add( list.add( Color.MAGENTAColor.MAGENTAColor.MAGENTAColor.MAGENTA ); ); ); ); // add a color object// add a color object// add a color object// add a color object
16 17 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < colors.length; count++ ); count < colors.length; count++ ); count < colors.length; count++ ); count < colors.length; count++ )
18 list.add( colors[ count ] ); list.add( colors[ count ] ); list.add( colors[ count ] ); list.add( colors[ count ] );
19 20 list.add( list.add( list.add( list.add( Color.CYANColor.CYANColor.CYANColor.CYAN ); ); ); ); // add a color object// add a color object// add a color object// add a color object
21 22 // output list contents// output list contents// output list contents// output list contents
23 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nArrayListnArrayListnArrayListnArrayList: ": ": ": " ););););
24 25 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ )
26 System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + " "" "" "" " ););););
27
Outline
CollectionTest.java
Line 29
Line 42
Line 45
Line 47
Line 48
28 28 28 28 // remove all String objects// remove all String objects// remove all String objects// remove all String objects
29 29 29 29 removeStringsremoveStringsremoveStringsremoveStrings( list );( list );( list );( list );
30 30 30 30
31 31 31 31 // output list contents// output list contents// output list contents// output list contents
32 32 32 32 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nnnn\\\\nArrayListnArrayListnArrayListnArrayList after calling after calling after calling after calling removeStringsremoveStringsremoveStringsremoveStrings: ": ": ": "););););
33 33 33 33
34 34 34 34 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ )
35 35 35 35 System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + " "" "" "" " ););););
36 36 36 36
37 37 37 37 } } } } // end constructor // end constructor // end constructor // end constructor CollectionTestCollectionTestCollectionTestCollectionTest
38 38 38 38
39 39 39 39 // remove String objects from Collection// remove String objects from Collection// remove String objects from Collection// remove String objects from Collection
40 40 40 40 privateprivateprivateprivate voidvoidvoidvoid removeStringsremoveStringsremoveStringsremoveStrings( Collection collection )( Collection collection )( Collection collection )( Collection collection )
41 41 41 41 {{{{
42 42 42 42 IteratorIteratorIteratorIterator iteratoriteratoriteratoriterator = = = = collection.iteratorcollection.iteratorcollection.iteratorcollection.iterator(); (); (); (); // get // get // get // get iteratoriteratoriteratoriterator
43 43 43 43
44 44 44 44 // loop while collection has items // loop while collection has items // loop while collection has items // loop while collection has items
45 45 45 45 whilewhilewhilewhile ( ( ( ( iterator.hasNextiterator.hasNextiterator.hasNextiterator.hasNext() ) () ) () ) () )
46 46 46 46
47 47 47 47 ifififif ( ( ( ( iterator.nextiterator.nextiterator.nextiterator.next() () () () instanceofinstanceofinstanceofinstanceof String ) String ) String ) String )
48 48 48 48 iterator.removeiterator.removeiterator.removeiterator.remove(); (); (); (); // remove String object // remove String object // remove String object // remove String object
49 49 49 49 }}}}
50 50 50 50
Outline
CollectionTest.java
51 51 51 51 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
52 52 52 52 {{{{
53 53 53 53 newnewnewnew CollectionTestCollectionTestCollectionTestCollectionTest();();();();
54 54 54 54 } } } }
55 55 55 55
56 56 56 56 } } } } // end class // end class // end class // end class CollectionTestCollectionTestCollectionTestCollectionTest
ArrayListArrayListArrayListArrayList::::java.awt.Color[rjava.awt.Color[rjava.awt.Color[rjava.awt.Color[r=255,g=0,b=255] red white blue =255,g=0,b=255] red white blue =255,g=0,b=255] red white blue =255,g=0,b=255] red white blue java.awt.Colorjava.awt.Colorjava.awt.Colorjava.awt.Color[r=0,g=255,b=255][r=0,g=255,b=255][r=0,g=255,b=255][r=0,g=255,b=255]
ArrayListArrayListArrayListArrayList after calling after calling after calling after calling removeStringsremoveStringsremoveStringsremoveStrings::::java.awt.Color[rjava.awt.Color[rjava.awt.Color[rjava.awt.Color[r=255,g=0,b=255] =255,g=0,b=255] =255,g=0,b=255] =255,g=0,b=255] java.awt.Color[rjava.awt.Color[rjava.awt.Color[rjava.awt.Color[r=0,g=255,b=255]=0,g=255,b=255]=0,g=255,b=255]=0,g=255,b=255]
Outline
ListTest.java
Lines 14-15
Line 23
Line 24
12 // Using // Using // Using // Using LinkListsLinkListsLinkListsLinkLists....
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass ListTestListTestListTestListTest {{{{
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String colors[] = { String colors[] = { String colors[] = { String colors[] = { "black""black""black""black", , , , "yellow""yellow""yellow""yellow", , , ,
7 "green""green""green""green", , , , "blue""blue""blue""blue", , , , "violet""violet""violet""violet", , , , "silver""silver""silver""silver" };};};};
8 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String colors2[] = { String colors2[] = { String colors2[] = { String colors2[] = { "gold""gold""gold""gold", , , , "white""white""white""white", , , ,
9 "brown""brown""brown""brown", , , , "blue""blue""blue""blue", , , , "gray""gray""gray""gray", , , , "silver""silver""silver""silver" };};};};
10 11 // set up and manipulate // set up and manipulate // set up and manipulate // set up and manipulate LinkedListLinkedListLinkedListLinkedList objectsobjectsobjectsobjects
12 publicpublicpublicpublic ListTestListTestListTestListTest()()()()
13 {{{{
14 List link = List link = List link = List link = newnewnewnew LinkedListLinkedListLinkedListLinkedList(); (); (); ();
15 List link2 = List link2 = List link2 = List link2 = newnewnewnew LinkedListLinkedListLinkedListLinkedList();();();();
16 17 // add elements to each list// add elements to each list// add elements to each list// add elements to each list
18 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < colors.length; count++ ) {; count < colors.length; count++ ) {; count < colors.length; count++ ) {; count < colors.length; count++ ) {
19 link.add( colors[ count ] ); link.add( colors[ count ] ); link.add( colors[ count ] ); link.add( colors[ count ] );
20 link2.add( colors2[ count ] );link2.add( colors2[ count ] );link2.add( colors2[ count ] );link2.add( colors2[ count ] );
21 }}}}
22 23 link.addAlllink.addAlllink.addAlllink.addAll( link2 ); ( link2 ); ( link2 ); ( link2 ); // concatenate lists// concatenate lists// concatenate lists// concatenate lists
24 link2 = link2 = link2 = link2 = nullnullnullnull; ; ; ; // release resources// release resources// release resources// release resources
25
Outline
ListTest.java
Lines 42-50
26 printListprintListprintListprintList( link );( link );( link );( link );
27 28 uppercaseStringsuppercaseStringsuppercaseStringsuppercaseStrings( link );( link );( link );( link );
29 30 printListprintListprintListprintList( link );( link );( link );( link );
31 32 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nDeletingnDeletingnDeletingnDeleting elements 4 to 6..."elements 4 to 6..."elements 4 to 6..."elements 4 to 6..." ););););
33 removeItemsremoveItemsremoveItemsremoveItems( link, ( link, ( link, ( link, 4444, , , , 7777 ););););
34 35 printListprintListprintListprintList( link );( link );( link );( link );
36 37 printReversedListprintReversedListprintReversedListprintReversedList( link );( link );( link );( link );
38 39 } } } } // end constructor // end constructor // end constructor // end constructor ListTestListTestListTestListTest
40 41 // output List contents// output List contents// output List contents// output List contents
42 publicpublicpublicpublic voidvoidvoidvoid printListprintListprintListprintList( List list )( List list )( List list )( List list )
43 {{{{
44 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nlistnlistnlistnlist: ": ": ": " ););););
45 46 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ ); count < list.size(); count++ )
47 System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + System.out.print( list.get( count ) + " "" "" "" " ););););
48 49 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println();();();();
50 } } } }
Outline
ListTest.java
Lines 53-63
Line 68
51 52 // locate String objects and convert to uppercase// locate String objects and convert to uppercase// locate String objects and convert to uppercase// locate String objects and convert to uppercase
53 privateprivateprivateprivate voidvoidvoidvoid uppercaseStringsuppercaseStringsuppercaseStringsuppercaseStrings( List list )( List list )( List list )( List list )
54 {{{{
55 ListIteratorListIteratorListIteratorListIterator iteratoriteratoriteratoriterator = = = = list.listIteratorlist.listIteratorlist.listIteratorlist.listIterator();();();();
56 57 whilewhilewhilewhile ( ( ( ( iterator.hasNextiterator.hasNextiterator.hasNextiterator.hasNext() ) {() ) {() ) {() ) {
58 Object object = Object object = Object object = Object object = iterator.nextiterator.nextiterator.nextiterator.next(); (); (); (); // get item// get item// get item// get item
59 60 ifififif ( object ( object ( object ( object instanceofinstanceofinstanceofinstanceof String ) String ) String ) String ) // check for String// check for String// check for String// check for String
61 iterator.setiterator.setiterator.setiterator.set( ( ( String ) object ).( ( ( String ) object ).( ( ( String ) object ).( ( ( String ) object ).toUpperCasetoUpperCasetoUpperCasetoUpperCase() ); () ); () ); () );
62 }}}}
63 }}}}
64 65 // obtain // obtain // obtain // obtain sublistsublistsublistsublist and use clear method to delete and use clear method to delete and use clear method to delete and use clear method to delete sublistsublistsublistsublist itemsitemsitemsitems
66 privateprivateprivateprivate voidvoidvoidvoid removeItemsremoveItemsremoveItemsremoveItems( List list, ( List list, ( List list, ( List list, intintintint start, start, start, start, intintintint end )end )end )end )
67 {{{{
68 list.subListlist.subListlist.subListlist.subList( start, end ).clear(); ( start, end ).clear(); ( start, end ).clear(); ( start, end ).clear(); // remove items// remove items// remove items// remove items
69 }}}}
70 71 // print reversed list// print reversed list// print reversed list// print reversed list
72 privateprivateprivateprivate voidvoidvoidvoid printReversedListprintReversedListprintReversedListprintReversedList( List list )( List list )( List list )( List list )
73 {{{{
74 ListIteratorListIteratorListIteratorListIterator iteratoriteratoriteratoriterator = = = = list.listIteratorlist.listIteratorlist.listIteratorlist.listIterator( list.size() );( list.size() );( list.size() );( list.size() );
75
Outline
ListTest.java
Line 79
Line 80
76 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nReversednReversednReversednReversed List:"List:"List:"List:" ););););
77 78 // print list in reverse order// print list in reverse order// print list in reverse order// print list in reverse order
79 whilewhilewhilewhile( ( ( ( iterator.hasPreviousiterator.hasPreviousiterator.hasPreviousiterator.hasPrevious() ) () ) () ) () )
80 System.out.print( System.out.print( System.out.print( System.out.print( iterator.previousiterator.previousiterator.previousiterator.previous() + () + () + () + " "" "" "" " ); ); ); );
81 }}}}
82 83 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
84 {{{{
85 newnewnewnew ListTestListTestListTestListTest();();();();
86 } } } }
87 88 } } } } // end class // end class // end class // end class ListTestListTestListTestListTest
list:list:list:list:black yellow green blue violet silver gold white brown blue grayblack yellow green blue violet silver gold white brown blue grayblack yellow green blue violet silver gold white brown blue grayblack yellow green blue violet silver gold white brown blue gray silversilversilversilver
list:list:list:list:BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAYBLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAYBLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAYBLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVERSILVERSILVERSILVER
Deleting elements 4 to 6...Deleting elements 4 to 6...Deleting elements 4 to 6...Deleting elements 4 to 6...list:list:list:list:BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVERBLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVERBLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVERBLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER
Reversed List:Reversed List:Reversed List:Reversed List:SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK
Outline
UsingToArray.java
Line 20
1 1 1 1 // Fig. 22.5: // Fig. 22.5: // Fig. 22.5: // Fig. 22.5: UsingToArray.javaUsingToArray.javaUsingToArray.javaUsingToArray.java
2 2 2 2 // Using method // Using method // Using method // Using method toArraytoArraytoArraytoArray....
3 3 3 3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 4 4 4
5 5 5 5 publicpublicpublicpublic classclassclassclass UsingToArrayUsingToArrayUsingToArrayUsingToArray {{{{
6 6 6 6
7 7 7 7 // create // create // create // create LinkedListLinkedListLinkedListLinkedList, add elements and convert to array, add elements and convert to array, add elements and convert to array, add elements and convert to array
8 8 8 8 publicpublicpublicpublic UsingToArrayUsingToArrayUsingToArrayUsingToArray()()()()
9 9 9 9 {{{{
10 10 10 10 String colors[] = { String colors[] = { String colors[] = { String colors[] = { "black""black""black""black", , , , "blue""blue""blue""blue", , , , "yellow""yellow""yellow""yellow" };};};};
11 11 11 11
12 12 12 12 LinkedListLinkedListLinkedListLinkedList links = links = links = links = newnewnewnew LinkedListLinkedListLinkedListLinkedList( ( ( ( Arrays.asListArrays.asListArrays.asListArrays.asList( colors ) );( colors ) );( colors ) );( colors ) );
13 13 13 13
14 14 14 14 links.addLastlinks.addLastlinks.addLastlinks.addLast( ( ( ( "red""red""red""red" ); ); ); ); // add as last item // add as last item // add as last item // add as last item
15 15 15 15 links.add( links.add( links.add( links.add( "pink""pink""pink""pink" ); ); ); ); // add to the end // add to the end // add to the end // add to the end
16 16 16 16 links.add( links.add( links.add( links.add( 3333, , , , "green""green""green""green" ); ); ); ); // add at 3rd index // add at 3rd index // add at 3rd index // add at 3rd index
17 17 17 17 links.addFirstlinks.addFirstlinks.addFirstlinks.addFirst( ( ( ( "cyan""cyan""cyan""cyan" ); ); ); ); // add as first item // add as first item // add as first item // add as first item
18 18 18 18
19 19 19 19 // get // get // get // get LinkedListLinkedListLinkedListLinkedList elements as an array elements as an array elements as an array elements as an array
20 20 20 20 colors = ( String [] ) colors = ( String [] ) colors = ( String [] ) colors = ( String [] ) links.toArraylinks.toArraylinks.toArraylinks.toArray( ( ( ( newnewnewnew String[ links.size() ] );String[ links.size() ] );String[ links.size() ] );String[ links.size() ] );
21 21 21 21
22 22 22 22 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "colors: ""colors: ""colors: ""colors: " ););););
23 23 23 23
Outline
UsingToArray.java
24 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < colors.length; count++ ); count < colors.length; count++ ); count < colors.length; count++ ); count < colors.length; count++ )
25 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( colors[ count ] );( colors[ count ] );( colors[ count ] );( colors[ count ] );
26 }}}}
27 28 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
29 {{{{
30 newnewnewnew UsingToArrayUsingToArrayUsingToArrayUsingToArray();();();();
31 } } } }
32 33 } } } } // end class // end class // end class // end class UsingToArrayUsingToArrayUsingToArrayUsingToArray
colors:colors:colors:colors:cyancyancyancyanblackblackblackblackblueblueblueblueyellowyellowyellowyellowgreengreengreengreenredredredredpinkpinkpinkpink
23
8.6 Algorithms
• Collections Framework provides set of algorithms– Implemented as static methods
• List algorithms
– sort
– binarySearch
– reverse
– shuffle
– fill
– copy
• Collection algorithms
– min
– max
24
8.6.1 Algorithm sortsortsortsort
• sort– Sorts List elements
• Order is determined by natural order of elements’ type
• Relatively fast
Outline
Sort1.java
Line 13
Line 18
12 // Using algorithm sort.// Using algorithm sort.// Using algorithm sort.// Using algorithm sort.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass Sort1 {Sort1 {Sort1 {Sort1 {
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String suits[] = String suits[] = String suits[] = String suits[] =
7 { { { { "Hearts""Hearts""Hearts""Hearts", , , , "Diamonds""Diamonds""Diamonds""Diamonds", , , , "Clubs""Clubs""Clubs""Clubs", , , , "Spades""Spades""Spades""Spades" };};};};
8 9 // display array elements// display array elements// display array elements// display array elements
10 publicpublicpublicpublic voidvoidvoidvoid printElementsprintElementsprintElementsprintElements()()()()
11 {{{{
12 // create // create // create // create ArrayListArrayListArrayListArrayList
13 List list = List list = List list = List list = newnewnewnew ArrayListArrayListArrayListArrayList( ( ( ( Arrays.asListArrays.asListArrays.asListArrays.asList( suits ) );( suits ) );( suits ) );( suits ) );
14 15 // output list// output list// output list// output list
16 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Unsorted array elements:"Unsorted array elements:"Unsorted array elements:"Unsorted array elements:\\\\n"n"n"n" + list );+ list );+ list );+ list );
17 18 Collections.sort( list ); Collections.sort( list ); Collections.sort( list ); Collections.sort( list ); // sort // sort // sort // sort ArrayListArrayListArrayListArrayList
19 20 // output list// output list// output list// output list
21 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Sorted array elements:"Sorted array elements:"Sorted array elements:"Sorted array elements:\\\\n"n"n"n" + list );+ list );+ list );+ list );
22 }}}}
23
Outline
Sort1.java
Unsorted array elements:Unsorted array elements:Unsorted array elements:Unsorted array elements:
[Hearts, Diamonds, Clubs, Spades][Hearts, Diamonds, Clubs, Spades][Hearts, Diamonds, Clubs, Spades][Hearts, Diamonds, Clubs, Spades]
Sorted array elements:Sorted array elements:Sorted array elements:Sorted array elements:
[Clubs, Diamonds, Hearts, Spades][Clubs, Diamonds, Hearts, Spades][Clubs, Diamonds, Hearts, Spades][Clubs, Diamonds, Hearts, Spades]
24 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
25 {{{{
26 newnewnewnew Sort1().printElements();Sort1().printElements();Sort1().printElements();Sort1().printElements();
27 } } } }
28 29 } } } } // end class Sort1// end class Sort1// end class Sort1// end class Sort1
Outline
Sort2.java
Line 18
Line 18
12 // Using a Comparator object with algorithm sort.// Using a Comparator object with algorithm sort.// Using a Comparator object with algorithm sort.// Using a Comparator object with algorithm sort.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass Sort2 {Sort2 {Sort2 {Sort2 {
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String suits[] = String suits[] = String suits[] = String suits[] =
7 { { { { "Hearts""Hearts""Hearts""Hearts", , , , "Diamonds""Diamonds""Diamonds""Diamonds", , , , "Clubs""Clubs""Clubs""Clubs", , , , "Spades""Spades""Spades""Spades" };};};};
8 9 // output List elements// output List elements// output List elements// output List elements
10 publicpublicpublicpublic voidvoidvoidvoid printElementsprintElementsprintElementsprintElements()()()()
11 {{{{
12 List list = List list = List list = List list = Arrays.asListArrays.asListArrays.asListArrays.asList( suits ); ( suits ); ( suits ); ( suits ); // create List// create List// create List// create List
13 14 // output List elements// output List elements// output List elements// output List elements
15 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Unsorted array elements:"Unsorted array elements:"Unsorted array elements:"Unsorted array elements:\\\\n"n"n"n" + list );+ list );+ list );+ list );
16 17 // sort in descending order using a comparator// sort in descending order using a comparator// sort in descending order using a comparator// sort in descending order using a comparator
18 Collections.sort( list, Collections.sort( list, Collections.sort( list, Collections.sort( list, Collections.reverseOrderCollections.reverseOrderCollections.reverseOrderCollections.reverseOrder() ); () ); () ); () );
19 20 // output List elements// output List elements// output List elements// output List elements
21 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Sorted list elements:"Sorted list elements:"Sorted list elements:"Sorted list elements:\\\\n"n"n"n" + list );+ list );+ list );+ list );
22 }}}}
23
Outline
Sort2.java
Unsorted array elements:Unsorted array elements:Unsorted array elements:Unsorted array elements:
[Hearts, Diamonds, Clubs, Spades][Hearts, Diamonds, Clubs, Spades][Hearts, Diamonds, Clubs, Spades][Hearts, Diamonds, Clubs, Spades]
Sorted list elements:Sorted list elements:Sorted list elements:Sorted list elements:
[Spades, Hearts, Diamonds, Clubs][Spades, Hearts, Diamonds, Clubs][Spades, Hearts, Diamonds, Clubs][Spades, Hearts, Diamonds, Clubs]
24 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
25 {{{{
26 newnewnewnew Sort2().printElements();Sort2().printElements();Sort2().printElements();Sort2().printElements();
27 } } } }
28 29 } } } } // end class Sort2// end class Sort2// end class Sort2// end class Sort2
Outline
Sort3.java
Line 21
12 // Creating a custom Comparator class.// Creating a custom Comparator class.// Creating a custom Comparator class.// Creating a custom Comparator class.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass Sort3 {Sort3 {Sort3 {Sort3 {
6 7 public voidpublic voidpublic voidpublic void printElementsprintElementsprintElementsprintElements()()()()
8 {{{{
9 List list = new List list = new List list = new List list = new ArrayListArrayListArrayListArrayList();();();(); // create List// create List// create List// create List
10 11 list.add( list.add( list.add( list.add( newnewnewnew Time2( Time2( Time2( Time2( 6666, , , , 24242424, , , , 34343434 ) );) );) );) );
12 list.add( list.add( list.add( list.add( newnewnewnew Time2( Time2( Time2( Time2( 18181818, , , , 14141414, , , , 05050505 ) );) );) );) );
13 list.add( list.add( list.add( list.add( newnewnewnew Time2( Time2( Time2( Time2( 8888, , , , 05050505, , , , 00000000 ) );) );) );) );
14 list.add( list.add( list.add( list.add( newnewnewnew Time2( Time2( Time2( Time2( 12121212, , , , 07070707, , , , 58585858 ) );) );) );) );
15 list.add( list.add( list.add( list.add( newnewnewnew Time2( Time2( Time2( Time2( 6666, , , , 14141414, , , , 22222222 ) );) );) );) );
16 17 // output List elements// output List elements// output List elements// output List elements
18 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println(((( "Unsorted array elements:"Unsorted array elements:"Unsorted array elements:"Unsorted array elements:\\\\n"n"n"n" + list );+ list );+ list );+ list );
19 20 // sort in order using a comparator// sort in order using a comparator// sort in order using a comparator// sort in order using a comparator
21 Collections.sort( list, Collections.sort( list, Collections.sort( list, Collections.sort( list, newnewnewnew TimeComparatorTimeComparatorTimeComparatorTimeComparator() );() );() );() );
22 23 // output List elements// output List elements// output List elements// output List elements
24 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Sorted list elements:"Sorted list elements:"Sorted list elements:"Sorted list elements:\\\\n"n"n"n" + list );+ list );+ list );+ list );
25 }}}}
26
Outline
Sort3.java
Line 32
Line 36
27 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
28 {{{{
29 newnewnewnew Sort2().printElements();Sort2().printElements();Sort2().printElements();Sort2().printElements();
30 } } } }
31 32 privateprivateprivateprivate classclassclassclass TimeComparatorTimeComparatorTimeComparatorTimeComparator implementsimplementsimplementsimplements Comparator {Comparator {Comparator {Comparator {
33 intintintint hourComparehourComparehourComparehourCompare, , , , minuteCompareminuteCompareminuteCompareminuteCompare, , , , secondComparesecondComparesecondComparesecondCompare;;;;
34 Time2 time1, time2;Time2 time1, time2;Time2 time1, time2;Time2 time1, time2;
35 36 publicpublicpublicpublic intintintint compare(Object object1, Object object2)compare(Object object1, Object object2)compare(Object object1, Object object2)compare(Object object1, Object object2)
37 {{{{
38 // cast the objects// cast the objects// cast the objects// cast the objects
39 time1 = (Time2)object1;time1 = (Time2)object1;time1 = (Time2)object1;time1 = (Time2)object1;
40 time2 = (Time2)object2;time2 = (Time2)object2;time2 = (Time2)object2;time2 = (Time2)object2;
41 42 hourComparehourComparehourComparehourCompare = = = = newnewnewnew Integer( time1.getHour() ).Integer( time1.getHour() ).Integer( time1.getHour() ).Integer( time1.getHour() ).compareTocompareTocompareTocompareTo((((
43 newnewnewnew Integer( time2.getHour() ) );Integer( time2.getHour() ) );Integer( time2.getHour() ) );Integer( time2.getHour() ) );
44 45 // test the hour first// test the hour first// test the hour first// test the hour first
46 ifififif ( ( ( ( hourComparehourComparehourComparehourCompare != != != != 0000 ))))
47 returnreturnreturnreturn hourComparehourComparehourComparehourCompare;;;;
48 49 minuteCompareminuteCompareminuteCompareminuteCompare = = = = newnewnewnew Integer( time1.getMinute() ).Integer( time1.getMinute() ).Integer( time1.getMinute() ).Integer( time1.getMinute() ).compareTocompareTocompareTocompareTo((((
50 newnewnewnew Integer( time2.getMinute() ) );Integer( time2.getMinute() ) );Integer( time2.getMinute() ) );Integer( time2.getMinute() ) );
51
Outline
Sort3.java
Unsorted array elements:Unsorted array elements:Unsorted array elements:Unsorted array elements:
[06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22][06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22][06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22][06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22]
Sorted list elements:Sorted list elements:Sorted list elements:Sorted list elements:
[06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05][06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05][06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05][06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05]
52 // then test the minute// then test the minute// then test the minute// then test the minute
53 ifififif ( ( ( ( minuteCompareminuteCompareminuteCompareminuteCompare != != != != 0000 ))))
54 returnreturnreturnreturn minuteCompareminuteCompareminuteCompareminuteCompare;;;;
55 56 secondComparesecondComparesecondComparesecondCompare = = = = newnewnewnew Integer( time1.getSecond() ).Integer( time1.getSecond() ).Integer( time1.getSecond() ).Integer( time1.getSecond() ).compareTocompareTocompareTocompareTo((((
57 newnewnewnew Integer( time2.getSecond() ) );Integer( time2.getSecond() ) );Integer( time2.getSecond() ) );Integer( time2.getSecond() ) );
58 59 returnreturnreturnreturn secondComparesecondComparesecondComparesecondCompare; ; ; ; // return result of comparing seconds// return result of comparing seconds// return result of comparing seconds// return result of comparing seconds
60 }}}}
61 62 } } } } // end class // end class // end class // end class TimeComparatorTimeComparatorTimeComparatorTimeComparator
63 64 } } } } // end class Sort3// end class Sort3// end class Sort3// end class Sort3
32
8.6.2 Algorithm shuffle
• shuffle– Randomly orders List elements
Outline
Cards.java
1 Cards.javaCards.javaCards.javaCards.java
2 // Using algorithm shuffle.// Using algorithm shuffle.// Using algorithm shuffle.// Using algorithm shuffle.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 // class to represent a Card in a deck of cards// class to represent a Card in a deck of cards// class to represent a Card in a deck of cards// class to represent a Card in a deck of cards
6 classclassclassclass Card {Card {Card {Card {
7 privateprivateprivateprivate String face;String face;String face;String face;
8 privateprivateprivateprivate String suit;String suit;String suit;String suit;
9 10 // initialize a Card// initialize a Card// initialize a Card// initialize a Card
11 publicpublicpublicpublic Card( String Card( String Card( String Card( String initialfaceinitialfaceinitialfaceinitialface, String , String , String , String initialSuitinitialSuitinitialSuitinitialSuit ))))
12 {{{{
13 face = face = face = face = initialfaceinitialfaceinitialfaceinitialface;;;;
14 suit = suit = suit = suit = initialSuitinitialSuitinitialSuitinitialSuit;;;;
15 }}}}
16 17 // return face of Card// return face of Card// return face of Card// return face of Card
18 publicpublicpublicpublic String String String String getFacegetFacegetFacegetFace() () () ()
19 { { { {
20 returnreturnreturnreturn face; face; face; face;
21 }}}}
22 23 // return suit of Card// return suit of Card// return suit of Card// return suit of Card
24 publicpublicpublicpublic String String String String getSuitgetSuitgetSuitgetSuit() () () ()
25 { { { {
26 returnreturnreturnreturn suit; suit; suit; suit;
27 }}}}
Outline
Cards.java
28 29 // return String representation of Card// return String representation of Card// return String representation of Card// return String representation of Card
30 publicpublicpublicpublic String String String String toStringtoStringtoStringtoString()()()()
31 {{{{
32 StringBufferStringBufferStringBufferStringBuffer buffer = buffer = buffer = buffer = newnewnewnew StringBufferStringBufferStringBufferStringBuffer( face + ( face + ( face + ( face + " of "" of "" of "" of " + suit );+ suit );+ suit );+ suit );
33 buffer.setLengthbuffer.setLengthbuffer.setLengthbuffer.setLength( ( ( ( 20202020 ););););
34 35 returnreturnreturnreturn buffer.toStringbuffer.toStringbuffer.toStringbuffer.toString();();();();
36 }}}}
37 38 } } } } // end class Card// end class Card// end class Card// end class Card
39 40 // class Cards declaration// class Cards declaration// class Cards declaration// class Cards declaration
41 publicpublicpublicpublic classclassclassclass Cards {Cards {Cards {Cards {
42 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String suits[] = String suits[] = String suits[] = String suits[] =
43 { { { { "Hearts""Hearts""Hearts""Hearts", , , , "Clubs""Clubs""Clubs""Clubs", , , , "Diamonds""Diamonds""Diamonds""Diamonds", , , , "Spades""Spades""Spades""Spades" };};};};
44 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String faces[] = { String faces[] = { String faces[] = { String faces[] = { "Ace""Ace""Ace""Ace", , , , "Deuce""Deuce""Deuce""Deuce", , , , "Three""Three""Three""Three",,,,
45 "Four""Four""Four""Four", , , , "Five""Five""Five""Five", , , , "Six""Six""Six""Six", , , , "Seven""Seven""Seven""Seven", , , , "Eight""Eight""Eight""Eight", , , , "Nine""Nine""Nine""Nine", , , , "Ten""Ten""Ten""Ten",,,,
46 "Jack""Jack""Jack""Jack", , , , "Queen""Queen""Queen""Queen", , , , "King""King""King""King" };};};};
47 privateprivateprivateprivate List list;List list;List list;List list;
48 49 // set up deck of Cards and shuffle// set up deck of Cards and shuffle// set up deck of Cards and shuffle// set up deck of Cards and shuffle
50 publicpublicpublicpublic Cards()Cards()Cards()Cards()
51 {{{{
52 Card deck[] = Card deck[] = Card deck[] = Card deck[] = newnewnewnew Card[ Card[ Card[ Card[ 52525252 ];];];];
53
Outline
Cards.java
Line 59
54 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < deck.length; count++ ); count < deck.length; count++ ); count < deck.length; count++ ); count < deck.length; count++ )
55 deck[ count ] = deck[ count ] = deck[ count ] = deck[ count ] = newnewnewnew Card( faces[ count % Card( faces[ count % Card( faces[ count % Card( faces[ count % 13131313 ],],],],
56 suits[ count / suits[ count / suits[ count / suits[ count / 13131313 ] );] );] );] );
57 58 list = list = list = list = Arrays.asListArrays.asListArrays.asListArrays.asList( deck ); ( deck ); ( deck ); ( deck ); // get List // get List // get List // get List
59 Collections.shuffle( list ); Collections.shuffle( list ); Collections.shuffle( list ); Collections.shuffle( list ); // shuffle deck// shuffle deck// shuffle deck// shuffle deck
60 }}}}
61 62 // output deck// output deck// output deck// output deck
63 publicpublicpublicpublic voidvoidvoidvoid printCardsprintCardsprintCardsprintCards()()()()
64 {{{{
65 intintintint half = list.size() / half = list.size() / half = list.size() / half = list.size() / 2222 ---- 1111;;;;
66 67 forforforfor ( ( ( ( intintintint i = i = i = i = 0000, j = half + , j = half + , j = half + , j = half + 1111; i <= half; i++, j++ ); i <= half; i++, j++ ); i <= half; i++, j++ ); i <= half; i++, j++ )
68 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( list.get( i ).( list.get( i ).( list.get( i ).( list.get( i ).toStringtoStringtoStringtoString() + list.get( j ) );() + list.get( j ) );() + list.get( j ) );() + list.get( j ) );
69 }}}}
70 71 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
72 {{{{
73 newnewnewnew Cards().printCardsCards().printCardsCards().printCardsCards().printCards();();();();
74 } } } }
75 76 } } } } // end class Cards// end class Cards// end class Cards// end class Cards
Outline
Cards.java
King of Diamonds Jack of SpadesKing of Diamonds Jack of SpadesKing of Diamonds Jack of SpadesKing of Diamonds Jack of Spades
Four of Diamonds Six of ClubsFour of Diamonds Six of ClubsFour of Diamonds Six of ClubsFour of Diamonds Six of Clubs
King of Hearts Nine of DiamondsKing of Hearts Nine of DiamondsKing of Hearts Nine of DiamondsKing of Hearts Nine of Diamonds
Three of Spades Four of SpadesThree of Spades Four of SpadesThree of Spades Four of SpadesThree of Spades Four of Spades
Four of Hearts Seven of SpadesFour of Hearts Seven of SpadesFour of Hearts Seven of SpadesFour of Hearts Seven of Spades
Five of Diamonds Eight of HeartsFive of Diamonds Eight of HeartsFive of Diamonds Eight of HeartsFive of Diamonds Eight of Hearts
Queen of Diamonds Five of HeartsQueen of Diamonds Five of HeartsQueen of Diamonds Five of HeartsQueen of Diamonds Five of Hearts
Seven of Diamonds Seven of HeartsSeven of Diamonds Seven of HeartsSeven of Diamonds Seven of HeartsSeven of Diamonds Seven of Hearts
Nine of Hearts Three of ClubsNine of Hearts Three of ClubsNine of Hearts Three of ClubsNine of Hearts Three of Clubs
Ten of Spades Deuce of HeartsTen of Spades Deuce of HeartsTen of Spades Deuce of HeartsTen of Spades Deuce of Hearts
Three of Hearts Ace of SpadesThree of Hearts Ace of SpadesThree of Hearts Ace of SpadesThree of Hearts Ace of Spades
Six of Hearts Eight of DiamondsSix of Hearts Eight of DiamondsSix of Hearts Eight of DiamondsSix of Hearts Eight of Diamonds
Six of Diamonds Deuce of ClubsSix of Diamonds Deuce of ClubsSix of Diamonds Deuce of ClubsSix of Diamonds Deuce of Clubs
Ace of Clubs Ten of DiamondsAce of Clubs Ten of DiamondsAce of Clubs Ten of DiamondsAce of Clubs Ten of Diamonds
Eight of Clubs Queen of HeartsEight of Clubs Queen of HeartsEight of Clubs Queen of HeartsEight of Clubs Queen of Hearts
Jack of Clubs Ten of ClubsJack of Clubs Ten of ClubsJack of Clubs Ten of ClubsJack of Clubs Ten of Clubs
Seven of Clubs Queen of SpadesSeven of Clubs Queen of SpadesSeven of Clubs Queen of SpadesSeven of Clubs Queen of Spades
Five of Clubs Six of SpadesFive of Clubs Six of SpadesFive of Clubs Six of SpadesFive of Clubs Six of Spades
Nine of Spades Nine of ClubsNine of Spades Nine of ClubsNine of Spades Nine of ClubsNine of Spades Nine of Clubs
King of Spades Ace of DiamondsKing of Spades Ace of DiamondsKing of Spades Ace of DiamondsKing of Spades Ace of Diamonds
Ten of Hearts Ace of HeartsTen of Hearts Ace of HeartsTen of Hearts Ace of HeartsTen of Hearts Ace of Hearts
Queen of Clubs Deuce of SpadesQueen of Clubs Deuce of SpadesQueen of Clubs Deuce of SpadesQueen of Clubs Deuce of Spades
Three of Diamonds King of ClubsThree of Diamonds King of ClubsThree of Diamonds King of ClubsThree of Diamonds King of Clubs
Four of Clubs Jack of DiamondsFour of Clubs Jack of DiamondsFour of Clubs Jack of DiamondsFour of Clubs Jack of Diamonds
Eight of Spades Five of SpadesEight of Spades Five of SpadesEight of Spades Five of SpadesEight of Spades Five of Spades
Jack of Hearts Deuce of DiamondsJack of Hearts Deuce of DiamondsJack of Hearts Deuce of DiamondsJack of Hearts Deuce of Diamonds
378.6.3 Algorithms reverse, fill, copy, maxand 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
Outline
Algorithms1.java
Line 19
Line 23
1 //////// Algorithms1.javaAlgorithms1.javaAlgorithms1.javaAlgorithms1.java
2 // Using algorithms reverse, fill, copy, min and max.// Using algorithms reverse, fill, copy, min and max.// Using algorithms reverse, fill, copy, min and max.// Using algorithms reverse, fill, copy, min and max.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass Algorithms1 {Algorithms1 {Algorithms1 {Algorithms1 {
6 privateprivateprivateprivate String letters[] = { String letters[] = { String letters[] = { String letters[] = { "P""P""P""P", , , , "C""C""C""C", , , , "M""M""M""M" }, }, }, }, lettersCopylettersCopylettersCopylettersCopy[];[];[];[];
7 privateprivateprivateprivate List list, List list, List list, List list, copyListcopyListcopyListcopyList;;;;
8 9 // create a List and manipulate it with methods from Collections// create a List and manipulate it with methods from Collections// create a List and manipulate it with methods from Collections// create a List and manipulate it with methods from Collections
10 publicpublicpublicpublic Algorithms1()Algorithms1()Algorithms1()Algorithms1()
11 {{{{
12 list = list = list = list = Arrays.asListArrays.asListArrays.asListArrays.asList( letters ); ( letters ); ( letters ); ( letters ); // get List// get List// get List// get List
13 lettersCopylettersCopylettersCopylettersCopy = = = = newnewnewnew String[ String[ String[ String[ 3333 ];];];];
14 copyListcopyListcopyListcopyList = = = = Arrays.asListArrays.asListArrays.asListArrays.asList( ( ( ( lettersCopylettersCopylettersCopylettersCopy ););););
15 16 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Initial list: ""Initial list: ""Initial list: ""Initial list: " ););););
17 output( list );output( list );output( list );output( list );
18 19 Collections.reverse( list ); Collections.reverse( list ); Collections.reverse( list ); Collections.reverse( list ); // reverse order// reverse order// reverse order// reverse order
20 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nAfternAfternAfternAfter calling reverse: "calling reverse: "calling reverse: "calling reverse: " ););););
21 output( list );output( list );output( list );output( list );
22 23 Collections.copy( Collections.copy( Collections.copy( Collections.copy( copyListcopyListcopyListcopyList, list ); , list ); , list ); , list ); // copy List// copy List// copy List// copy List
24 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nAfternAfternAfternAfter copying: "copying: "copying: "copying: " ););););
25 output( output( output( output( copyListcopyListcopyListcopyList ););););
26
Outline
Algorithms1.java
Line 27
Line 41
Line 42
27 Collections.fill( list, Collections.fill( list, Collections.fill( list, Collections.fill( list, "R""R""R""R" ); ); ); ); // fill list with // fill list with // fill list with // fill list with RsRsRsRs
28 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nAfternAfternAfternAfter calling fill: "calling fill: "calling fill: "calling fill: " ););););
29 output( list );output( list );output( list );output( list );
30 31 } } } } // end constructor// end constructor// end constructor// end constructor
32 33 // output List information// output List information// output List information// output List information
34 privateprivateprivateprivate voidvoidvoidvoid output( List output( List output( List output( List listReflistReflistReflistRef ))))
35 {{{{
36 System.out.print( System.out.print( System.out.print( System.out.print( "The list is: ""The list is: ""The list is: ""The list is: " ););););
37 38 forforforfor ( ( ( ( intintintint k = k = k = k = 0000; k < ; k < ; k < ; k < listRef.sizelistRef.sizelistRef.sizelistRef.size(); k++ )(); k++ )(); k++ )(); k++ )
39 System.out.print( System.out.print( System.out.print( System.out.print( listRef.getlistRef.getlistRef.getlistRef.get( k ) + ( k ) + ( k ) + ( k ) + " "" "" "" " ););););
40 41 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nMaxnMaxnMaxnMax: ": ": ": " + Collections.max( + Collections.max( + Collections.max( + Collections.max( listReflistReflistReflistRef ) );) );) );) );
42 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( " Min: "" Min: "" Min: "" Min: " + Collections.min( + Collections.min( + Collections.min( + Collections.min( listReflistReflistReflistRef ) );) );) );) );
43 }}}}
44 45 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
46 {{{{
47 newnewnewnew Algorithms1();Algorithms1();Algorithms1();Algorithms1();
48 } } } }
49 50 } } } } // end class Algorithms1// end class Algorithms1// end class Algorithms1// end class Algorithms1
Outline
Algorithms1.java
Initial list:Initial list:Initial list:Initial list:The list is: P C MThe list is: P C MThe list is: P C MThe list is: P C MMax: P Min: CMax: P Min: CMax: P Min: CMax: P Min: C
After calling reverse:After calling reverse:After calling reverse:After calling reverse:The list is: M C PThe list is: M C PThe list is: M C PThe list is: M C PMax: P Min: CMax: P Min: CMax: P Min: CMax: P Min: C
After copying:After copying:After copying:After copying:The list is: M C PThe list is: M C PThe list is: M C PThe list is: M C PMax: P Min: CMax: P Min: CMax: P Min: CMax: P Min: C
After calling fill:After calling fill:After calling fill:After calling fill:The list is: R R RThe list is: R R RThe list is: R R RThe list is: R R RMax: R Min: RMax: R Min: RMax: R Min: RMax: R Min: R
41
8.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
Outline
BinarySearchTest.java
Line 14
1 // // // // BinarySearchTest.javaBinarySearchTest.javaBinarySearchTest.javaBinarySearchTest.java
2 // Using algorithm // Using algorithm // Using algorithm // Using algorithm binarySearchbinarySearchbinarySearchbinarySearch....
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass BinarySearchTestBinarySearchTestBinarySearchTestBinarySearchTest {{{{
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String colors[] = { String colors[] = { String colors[] = { String colors[] = { "red""red""red""red", , , , "white""white""white""white", , , ,
7 "blue""blue""blue""blue", , , , "black""black""black""black", , , , "yellow""yellow""yellow""yellow", , , , "purple""purple""purple""purple", , , , "tan""tan""tan""tan", , , , "pink""pink""pink""pink" };};};};
8 privateprivateprivateprivate List list; List list; List list; List list; // List reference// List reference// List reference// List reference
9 10 // create, sort and output list // create, sort and output list // create, sort and output list // create, sort and output list
11 publicpublicpublicpublic BinarySearchTestBinarySearchTestBinarySearchTestBinarySearchTest()()()()
12 {{{{
13 list = list = list = list = newnewnewnew ArrayListArrayListArrayListArrayList( ( ( ( Arrays.asListArrays.asListArrays.asListArrays.asList( colors ) ); ( colors ) ); ( colors ) ); ( colors ) );
14 Collections.sort( list ); Collections.sort( list ); Collections.sort( list ); Collections.sort( list ); // sort the // sort the // sort the // sort the ArrayListArrayListArrayListArrayList
15 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "Sorted "Sorted "Sorted "Sorted ArrayListArrayListArrayListArrayList: ": ": ": " + list );+ list );+ list );+ list );
16 }}}}
17 18 // search list for various values// search list for various values// search list for various values// search list for various values
19 privateprivateprivateprivate voidvoidvoidvoid printSearchResultsprintSearchResultsprintSearchResultsprintSearchResults()()()()
20 {{{{
21 printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( colors[ ( colors[ ( colors[ ( colors[ 3333 ] ); ] ); ] ); ] ); // first item// first item// first item// first item
22 printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( colors[ ( colors[ ( colors[ ( colors[ 0000 ] ); ] ); ] ); ] ); // middle item// middle item// middle item// middle item
23 printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( colors[ ( colors[ ( colors[ ( colors[ 7777 ] ); ] ); ] ); ] ); // last item// last item// last item// last item
24 printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( ( ( ( "aardvark""aardvark""aardvark""aardvark" ); ); ); ); // below lowest// below lowest// below lowest// below lowest
25 printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( ( ( ( "goat""goat""goat""goat" ); ); ); ); // does not exist// does not exist// does not exist// does not exist
26 printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( ( ( ( "zebra""zebra""zebra""zebra" ); ); ); ); // does not exist// does not exist// does not exist// does not exist
27 }}}}
28
Outline
BinarySearchTest.java
Line 35
29 29 29 29 // helper method to perform searches// helper method to perform searches// helper method to perform searches// helper method to perform searches
30 30 30 30 privateprivateprivateprivate voidvoidvoidvoid printSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelperprintSearchResultsHelper( String key )( String key )( String key )( String key )
31 31 31 31 {{{{
32 32 32 32 intintintint result = result = result = result = 0000;;;;
33 33 33 33
34 34 34 34 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nSearchingnSearchingnSearchingnSearching for: "for: "for: "for: " + key );+ key );+ key );+ key );
35 35 35 35 result = result = result = result = Collections.binarySearchCollections.binarySearchCollections.binarySearchCollections.binarySearch( list, key );( list, key );( list, key );( list, key );
36 36 36 36 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( result >= ( ( result >= ( ( result >= ( ( result >= 0000 ? ? ? ? "Found at index ""Found at index ""Found at index ""Found at index " + result :+ result :+ result :+ result :
37 37 37 37 "Not Found (""Not Found (""Not Found (""Not Found (" + result + + result + + result + + result + ")"")"")"")" ) );) );) );) );
38 38 38 38 }}}}
39 39 39 39
40 40 40 40 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
41 41 41 41 {{{{
42 42 42 42 newnewnewnew BinarySearchTest().printSearchResultsBinarySearchTest().printSearchResultsBinarySearchTest().printSearchResultsBinarySearchTest().printSearchResults();();();();
43 43 43 43 } } } }
44 44 44 44
45 45 45 45 } } } } // end class // end class // end class // end class BinarySearchTestBinarySearchTestBinarySearchTestBinarySearchTest
Sorted Sorted Sorted Sorted ArrayListArrayListArrayListArrayList: black blue pink purple red tan white yellow: black blue pink purple red tan white yellow: black blue pink purple red tan white yellow: black blue pink purple red tan white yellowSearching for: blackSearching for: blackSearching for: blackSearching for: blackFound at index 0Found at index 0Found at index 0Found at index 0
Searching for: redSearching for: redSearching for: redSearching for: redFound at index 4Found at index 4Found at index 4Found at index 4
Searching for: pinkSearching for: pinkSearching for: pinkSearching for: pinkFound at index 2Found at index 2Found at index 2Found at index 2
Searching for: aardvarkSearching for: aardvarkSearching for: aardvarkSearching for: aardvarkNot Found (Not Found (Not Found (Not Found (----1)1)1)1)
Searching for: goatSearching for: goatSearching for: goatSearching for: goatNot Found (Not Found (Not Found (Not Found (----3)3)3)3)
Searching for: zebraSearching for: zebraSearching for: zebraSearching for: zebraNot Found (Not Found (Not Found (Not Found (----9)9)9)9)
44
8.7 Sets
• Set– Collection that contains unique elements
– HashSet
• Stores elements in hash table
– TreeSet
• Stores elements in tree
Outline
SetTest.java
Line 22
1 // // // // SetTest.javaSetTest.javaSetTest.javaSetTest.java
2 // Using a // Using a // Using a // Using a HashSetHashSetHashSetHashSet to remove duplicates.to remove duplicates.to remove duplicates.to remove duplicates.
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass SetTestSetTestSetTestSetTest {{{{
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String colors[] = { String colors[] = { String colors[] = { String colors[] = { "red""red""red""red", , , , "white""white""white""white", , , , "blue""blue""blue""blue",,,,
7 "green""green""green""green", , , , "gray""gray""gray""gray", , , , "orange""orange""orange""orange", , , , "tan""tan""tan""tan", , , , "white""white""white""white", , , , "cyan""cyan""cyan""cyan",,,,
8 "peach""peach""peach""peach", , , , "gray""gray""gray""gray", , , , "orange""orange""orange""orange" };};};};
9 10 // create and output // create and output // create and output // create and output ArrayListArrayListArrayListArrayList
11 publicpublicpublicpublic SetTestSetTestSetTestSetTest()()()()
12 {{{{
13 List list = List list = List list = List list = newnewnewnew ArrayListArrayListArrayListArrayList( ( ( ( Arrays.asListArrays.asListArrays.asListArrays.asList( colors ) );( colors ) );( colors ) );( colors ) );
14 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"ArrayListArrayListArrayListArrayList: ": ": ": " + list );+ list );+ list );+ list );
15 printNonDuplicatesprintNonDuplicatesprintNonDuplicatesprintNonDuplicates( list );( list );( list );( list );
16 }}}}
17 18 // create set from array to eliminate duplicates// create set from array to eliminate duplicates// create set from array to eliminate duplicates// create set from array to eliminate duplicates
19 privateprivateprivateprivate voidvoidvoidvoid printNonDuplicatesprintNonDuplicatesprintNonDuplicatesprintNonDuplicates( Collection collection )( Collection collection )( Collection collection )( Collection collection )
20 {{{{
21 // create a // create a // create a // create a HashSetHashSetHashSetHashSet and obtain its and obtain its and obtain its and obtain its iteratoriteratoriteratoriterator
22 Set set = Set set = Set set = Set set = newnewnewnew HashSetHashSetHashSetHashSet( collection ); ( collection ); ( collection ); ( collection );
23 IteratorIteratorIteratorIterator iteratoriteratoriteratoriterator = = = = set.iteratorset.iteratorset.iteratorset.iterator(); (); (); ();
24 25 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( """"\\\\nNonduplicatesnNonduplicatesnNonduplicatesnNonduplicates are: "are: "are: "are: " ););););
26
Outline
SetTest.java
Lines 27-28
27 whilewhilewhilewhile ( ( ( ( iterator.hasNextiterator.hasNextiterator.hasNextiterator.hasNext() )() )() )() )
28 System.out.print( System.out.print( System.out.print( System.out.print( iterator.nextiterator.nextiterator.nextiterator.next() + () + () + () + " "" "" "" " ););););
29 30 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println();();();();
31 }}}}
32 33 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
34 {{{{
35 newnewnewnew SetTestSetTestSetTestSetTest();();();();
36 } } } }
37 38 } } } } // end class // end class // end class // end class SetTestSetTestSetTestSetTest
ArrayListArrayListArrayListArrayList: [red, white, blue, green, gray, orange, tan, white, cyan, : [red, white, blue, green, gray, orange, tan, white, cyan, : [red, white, blue, green, gray, orange, tan, white, cyan, : [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange]peach, gray, orange]peach, gray, orange]peach, gray, orange]
NonduplicatesNonduplicatesNonduplicatesNonduplicates are:are:are:are:red cyan white tan gray green orange blue peachred cyan white tan gray green orange blue peachred cyan white tan gray green orange blue peachred cyan white tan gray green orange blue peach
Outline
SortedSetTest.java
Line 12
Line 19
Line 23
Lines 26-27
1 // // // // SortedSetTest.javaSortedSetTest.javaSortedSetTest.javaSortedSetTest.java
2 // Using // Using // Using // Using TreeSetTreeSetTreeSetTreeSet and and and and SortedSetSortedSetSortedSetSortedSet....
3 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
4 5 publicpublicpublicpublic classclassclassclass SortedSetTestSortedSetTestSortedSetTestSortedSetTest {{{{
6 privateprivateprivateprivate staticstaticstaticstatic finalfinalfinalfinal String names[] = { String names[] = { String names[] = { String names[] = { "yellow""yellow""yellow""yellow", , , , "green""green""green""green",,,,
7 "black""black""black""black", , , , "tan""tan""tan""tan", , , , "grey""grey""grey""grey", , , , "white""white""white""white", , , , "orange""orange""orange""orange", , , , "red""red""red""red", , , , "green""green""green""green" };};};};
8 9 // create a sorted set with // create a sorted set with // create a sorted set with // create a sorted set with TreeSetTreeSetTreeSetTreeSet, then manipulate it, then manipulate it, then manipulate it, then manipulate it
10 publicpublicpublicpublic SortedSetTestSortedSetTestSortedSetTestSortedSetTest()()()()
11 {{{{
12 SortedSetSortedSetSortedSetSortedSet tree = tree = tree = tree = newnewnewnew TreeSetTreeSetTreeSetTreeSet( ( ( ( Arrays.asListArrays.asListArrays.asListArrays.asList( names ) );( names ) );( names ) );( names ) );
13 14 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "set: ""set: ""set: ""set: " ););););
15 printSetprintSetprintSetprintSet( tree );( tree );( tree );( tree );
16 17 // get // get // get // get headSetheadSetheadSetheadSet based upon "orange"based upon "orange"based upon "orange"based upon "orange"
18 System.out.print( System.out.print( System.out.print( System.out.print( """"\\\\nheadSetnheadSetnheadSetnheadSet ((((\\\\"orange"orange"orange"orange\\\\"): ""): ""): ""): " ););););
19 printSetprintSetprintSetprintSet( ( ( ( tree.headSettree.headSettree.headSettree.headSet( ( ( ( "orange""orange""orange""orange" ) );) );) );) );
20 21 // get // get // get // get tailSettailSettailSettailSet based upon "orange"based upon "orange"based upon "orange"based upon "orange"
22 System.out.print( System.out.print( System.out.print( System.out.print( """"tailSettailSettailSettailSet ((((\\\\"orange"orange"orange"orange\\\\"): ""): ""): ""): " ););););
23 printSetprintSetprintSetprintSet( ( ( ( tree.tailSettree.tailSettree.tailSettree.tailSet( ( ( ( "orange""orange""orange""orange" ) );) );) );) );
24 25 // get first and last elements// get first and last elements// get first and last elements// get first and last elements
26 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "first: ""first: ""first: ""first: " + tree.first() );+ tree.first() );+ tree.first() );+ tree.first() );
27 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println( ( ( ( "last : ""last : ""last : ""last : " + tree.last() );+ tree.last() );+ tree.last() );+ tree.last() );
28 }}}}
29
Outline
SortedSetTest.java
Lines 35-36
30 // output set// output set// output set// output set
31 privateprivateprivateprivate voidvoidvoidvoid printSetprintSetprintSetprintSet( ( ( ( SortedSetSortedSetSortedSetSortedSet set )set )set )set )
32 {{{{
33 IteratorIteratorIteratorIterator iteratoriteratoriteratoriterator = = = = set.iteratorset.iteratorset.iteratorset.iterator();();();();
34 35 whilewhilewhilewhile ( ( ( ( iterator.hasNextiterator.hasNextiterator.hasNextiterator.hasNext() ) () ) () ) () )
36 System.out.print( System.out.print( System.out.print( System.out.print( iterator.nextiterator.nextiterator.nextiterator.next() + () + () + () + " "" "" "" " ););););
37 38 System.out.printlnSystem.out.printlnSystem.out.printlnSystem.out.println();();();();
39 } } } }
40 41 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
42 {{{{
43 newnewnewnew SortedSetTestSortedSetTestSortedSetTestSortedSetTest();();();();
44 } } } }
45 46 } } } } // end class // end class // end class // end class SortedSetTestSortedSetTestSortedSetTestSortedSetTest
set:set:set:set:black green grey orange red tan white yellowblack green grey orange red tan white yellowblack green grey orange red tan white yellowblack green grey orange red tan white yellow
headSetheadSetheadSetheadSet ("orange"): black green grey("orange"): black green grey("orange"): black green grey("orange"): black green greytailSettailSettailSettailSet ("orange"): orange red tan white yellow("orange"): orange red tan white yellow("orange"): orange red tan white yellow("orange"): orange red tan white yellowfirst: blackfirst: blackfirst: blackfirst: blacklast : yellowlast : yellowlast : yellowlast : yellow
49
8.8 Maps
• Map– Associates keys to values
– Cannot contain duplicate keys• Called one-to-one mapping
Outline
MapTest.java
Line 21
1 // // // // WordTypeCount.javaWordTypeCount.javaWordTypeCount.javaWordTypeCount.java
2 // Program counts the number of occurrences of each word in a st// Program counts the number of occurrences of each word in a st// Program counts the number of occurrences of each word in a st// Program counts the number of occurrences of each word in a stringringringring
3 importimportimportimport java.awtjava.awtjava.awtjava.awt.*;.*;.*;.*;
4 importimportimportimport java.awt.eventjava.awt.eventjava.awt.eventjava.awt.event.*;.*;.*;.*;
5 importimportimportimport java.util.*;java.util.*;java.util.*;java.util.*;
6 importimportimportimport javax.swingjavax.swingjavax.swingjavax.swing.*;.*;.*;.*;
7 8 public classpublic classpublic classpublic class WordTypeCountWordTypeCountWordTypeCountWordTypeCount extendsextendsextendsextends JFrameJFrameJFrameJFrame {{{{
9 privateprivateprivateprivate JTextAreaJTextAreaJTextAreaJTextArea inputFieldinputFieldinputFieldinputField;;;;
10 privateprivateprivateprivate JLabelJLabelJLabelJLabel prompt;prompt;prompt;prompt;
11 privateprivateprivateprivate JTextAreaJTextAreaJTextAreaJTextArea display;display;display;display;
12 privateprivateprivateprivate JButtonJButtonJButtonJButton goButtongoButtongoButtongoButton;;;;
13 14 privateprivateprivateprivate Map map;Map map;Map map;Map map;
15 16 publicpublicpublicpublic WordTypeCountWordTypeCountWordTypeCountWordTypeCount()()()()
17 {{{{
18 supersupersupersuper( ( ( ( "Word Type Count""Word Type Count""Word Type Count""Word Type Count" ););););
19 inputFieldinputFieldinputFieldinputField = = = = newnewnewnew JTextAreaJTextAreaJTextAreaJTextArea( ( ( ( 3333, , , , 20202020 ););););
20 21 map = map = map = map = newnewnewnew HashMapHashMapHashMapHashMap();();();();
22 23 goButtongoButtongoButtongoButton = = = = newnewnewnew JButtonJButtonJButtonJButton( ( ( ( "Go" "Go" "Go" "Go" ););););
24 goButton.addActionListenergoButton.addActionListenergoButton.addActionListenergoButton.addActionListener((((
25
Outline
MapTest.java
26 newnewnewnew ActionListenerActionListenerActionListenerActionListener() { () { () { () { // inner class// inner class// inner class// inner class
27 28 public voidpublic voidpublic voidpublic void actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent event )event )event )event )
29 {{{{
30 createMapcreateMapcreateMapcreateMap();();();();
31 display.setTextdisplay.setTextdisplay.setTextdisplay.setText( ( ( ( createOutputcreateOutputcreateOutputcreateOutput() );() );() );() );
32 }}}}
33 34 } } } } // end inner class// end inner class// end inner class// end inner class
35 36 ); ); ); ); // end call to // end call to // end call to // end call to addActionListeneraddActionListeneraddActionListeneraddActionListener
37 38 prompt = prompt = prompt = prompt = newnewnewnew JLabelJLabelJLabelJLabel( ( ( ( "Enter a string:" "Enter a string:" "Enter a string:" "Enter a string:" ););););
39 display = display = display = display = newnewnewnew JTextAreaJTextAreaJTextAreaJTextArea( ( ( ( 15151515, , , , 20202020 ););););
40 display.setEditabledisplay.setEditabledisplay.setEditabledisplay.setEditable( ( ( ( falsefalsefalsefalse ););););
41 42 JScrollPaneJScrollPaneJScrollPaneJScrollPane displayScrollPanedisplayScrollPanedisplayScrollPanedisplayScrollPane = = = = newnewnewnew JScrollPaneJScrollPaneJScrollPaneJScrollPane( display );( display );( display );( display );
43 44 // add components to GUI// add components to GUI// add components to GUI// add components to GUI
45 Container container = Container container = Container container = Container container = getContentPanegetContentPanegetContentPanegetContentPane();();();();
46 container.setLayoutcontainer.setLayoutcontainer.setLayoutcontainer.setLayout( ( ( ( newnewnewnew FlowLayoutFlowLayoutFlowLayoutFlowLayout() );() );() );() );
47 container.add( prompt );container.add( prompt );container.add( prompt );container.add( prompt );
48 container.add( container.add( container.add( container.add( inputFieldinputFieldinputFieldinputField ););););
49 container.add( container.add( container.add( container.add( goButtongoButtongoButtongoButton ););););
50 container.add( container.add( container.add( container.add( displayScrollPanedisplayScrollPanedisplayScrollPanedisplayScrollPane ););););
51
Outline
MapTest.java
Line 69
Lines 72 and 75
52 52 52 52 setSizesetSizesetSizesetSize( ( ( ( 400400400400, , , , 400400400400 ););););
53 53 53 53 show();show();show();show();
54 54 54 54
55 55 55 55 } } } } // end constructor// end constructor// end constructor// end constructor
56 56 56 56
57 57 57 57 // create map from user input// create map from user input// create map from user input// create map from user input
58 58 58 58 private voidprivate voidprivate voidprivate void createMapcreateMapcreateMapcreateMap()()()()
59 59 59 59 {{{{
60 60 60 60 String input = String input = String input = String input = inputField.getTextinputField.getTextinputField.getTextinputField.getText();();();();
61 61 61 61 StringTokenizerStringTokenizerStringTokenizerStringTokenizer tokenizertokenizertokenizertokenizer = = = = newnewnewnew StringTokenizerStringTokenizerStringTokenizerStringTokenizer( input );( input );( input );( input );
62 62 62 62
63 63 63 63 whilewhilewhilewhile ( ( ( ( tokenizer.hasMoreTokenstokenizer.hasMoreTokenstokenizer.hasMoreTokenstokenizer.hasMoreTokens() ) {() ) {() ) {() ) {
64 64 64 64 String word = String word = String word = String word = tokenizer.nextToken().toLowerCasetokenizer.nextToken().toLowerCasetokenizer.nextToken().toLowerCasetokenizer.nextToken().toLowerCase(); (); (); (); // get word// get word// get word// get word
65 65 65 65
66 66 66 66 // if the map contains the word// if the map contains the word// if the map contains the word// if the map contains the word
67 67 67 67 ifififif ( ( ( ( map.containsKeymap.containsKeymap.containsKeymap.containsKey( word ) ) {( word ) ) {( word ) ) {( word ) ) {
68 68 68 68
69 69 69 69 Integer count = (Integer) map.get( word ); Integer count = (Integer) map.get( word ); Integer count = (Integer) map.get( word ); Integer count = (Integer) map.get( word ); // get value// get value// get value// get value
70 70 70 70
71 71 71 71 // increment value// increment value// increment value// increment value
72 72 72 72 map.put( word, map.put( word, map.put( word, map.put( word, newnewnewnew Integer( Integer( Integer( Integer( count.intValuecount.intValuecount.intValuecount.intValue() + () + () + () + 1111 ) );) );) );) );
73 73 73 73 }}}}
74 74 74 74 elseelseelseelse // otherwise add word with a value of 1 to map// otherwise add word with a value of 1 to map// otherwise add word with a value of 1 to map// otherwise add word with a value of 1 to map
75 75 75 75 map.put( word, map.put( word, map.put( word, map.put( word, newnewnewnew Integer( Integer( Integer( Integer( 1111 ) );) );) );) );
76 76 76 76
77 77 77 77 } } } } // end while// end while// end while// end while
78 78 78 78
79 79 79 79 } } } } // end method // end method // end method // end method createMapcreateMapcreateMapcreateMap
Outline
MapTest.java
80 81 // create string containing map values// create string containing map values// create string containing map values// create string containing map values
82 privateprivateprivateprivate String String String String createOutputcreateOutputcreateOutputcreateOutput() { () { () { () {
83 StringBufferStringBufferStringBufferStringBuffer output = output = output = output = newnewnewnew StringBufferStringBufferStringBufferStringBuffer( ( ( ( """""""" ););););
84 IteratorIteratorIteratorIterator keys = keys = keys = keys = map.keySet().iteratormap.keySet().iteratormap.keySet().iteratormap.keySet().iterator();();();();
85 86 // iterate through the keys// iterate through the keys// iterate through the keys// iterate through the keys
87 whilewhilewhilewhile ( ( ( ( keys.hasNextkeys.hasNextkeys.hasNextkeys.hasNext() ) {() ) {() ) {() ) {
88 Object Object Object Object currentKeycurrentKeycurrentKeycurrentKey = keys.next();= keys.next();= keys.next();= keys.next();
89 90 // output the key// output the key// output the key// output the key----value pairsvalue pairsvalue pairsvalue pairs
91 output.append( output.append( output.append( output.append( currentKeycurrentKeycurrentKeycurrentKey + + + + """"\\\\t"t"t"t" + + + +
92 map.get( map.get( map.get( map.get( currentKeycurrentKeycurrentKeycurrentKey ) + ) + ) + ) + """"\\\\n" )n" )n" )n" );;;;
93 }}}}
94 95 output.append( output.append( output.append( output.append( "size: " "size: " "size: " "size: " + map.size() ++ map.size() ++ map.size() ++ map.size() + """"\\\\n"n"n"n" ););););
96 output.append( output.append( output.append( output.append( """"isEmptyisEmptyisEmptyisEmpty: ": ": ": " + + + + map.isEmptymap.isEmptymap.isEmptymap.isEmpty() + () + () + () + """"\\\\n"n"n"n" ););););
97 98 return return return return output.toStringoutput.toStringoutput.toStringoutput.toString();();();();
99 100 } } } } // end method // end method // end method // end method createOutputcreateOutputcreateOutputcreateOutput
101
Outline
MapTest.java
102 public static voidpublic static voidpublic static voidpublic static void main( String main( String main( String main( String argsargsargsargs[] )[] )[] )[] )
103 {{{{
104 WordTypeCountWordTypeCountWordTypeCountWordTypeCount application = application = application = application = newnewnewnew WordTypeCountWordTypeCountWordTypeCountWordTypeCount();();();();
105 application.setDefaultCloseOperationapplication.setDefaultCloseOperationapplication.setDefaultCloseOperationapplication.setDefaultCloseOperation( ( ( ( JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE ););););
106 }}}}
107 108 } } } } // end class // end class // end class // end class WordTypeCountWordTypeCountWordTypeCountWordTypeCount
55
8.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
56
8.9 Synchronization Wrappers (cont.)
publicpublicpublicpublic staticstaticstaticstatic 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. 8.15 Synchronization wrapper methods.
57
8.10 Unmodifiable Wrappers
• Unmodifiable wrappers– Converting collections to unmodifiable collections
– Throw UnsorrtedOperationException if attempts are made to modify the collection
58
8.10 Unmodifiable Wrappers
publicpublicpublicpublic staticstaticstaticstatic 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. 8.16 Unmodifiable wrapper methods.
59
8.11 Abstract Implementations
• Abstract implementations– Offer “bare bones” implementation of collection interfaces
• Programmers can “flesh out” customizable implementations
– AbstractCollection
– AbstractList
– AbstractMap
– AbstractSequentialList
– AbstractSet
608.12 (Optional) Discovering Design Patterns: Design Patterns Used in
Package java.util
• Design patterns in package java.util
61
8.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
62
8.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
63
8.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