Grouping Objects 3 Iterators, collections and the while loop.

43
Grouping Objects 3 Grouping Objects 3 Iterators, collections and the while loop Iterators, collections and the while loop
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    237
  • download

    0

Transcript of Grouping Objects 3 Iterators, collections and the while loop.

Grouping Objects 3Grouping Objects 3Iterators, collections and the while loopIterators, collections and the while loop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

IteratorsThe The for-eachfor-each loop is a simple way of iterating through loop is a simple way of iterating through everyevery element of a collection. element of a collection.

The The whilewhile loop gives a way of iterating through loop gives a way of iterating through somesome elements of a collection – it lets us stop when we’ve elements of a collection – it lets us stop when we’ve had enough had enough (e.g. because we found something we were (e.g. because we found something we were looking for)looking for)..

In the In the whilewhile loops loops seen before, we had to initialise an seen before, we had to initialise an indexindex variable variable (e.g. to(e.g. to 00)) into the collection, use it into the collection, use it (to (to get elements from the collection)get elements from the collection) and maintain and maintain (e.g. (e.g. increment)increment) it within the it within the whilewhile loop. loop.

IteratorsIterators – in conjunction with a – in conjunction with a whilewhile loop – loop – simplify simplify (partial)(partial) iteration through a collection iteration through a collection.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

while the value of index is less than the size of the collection, do print the note at position index and, then, increment index.

/**/** * List all notes in the notebook.* List all notes in the notebook. */*/public void listNotes()public void listNotes(){{ int index = 0;int index = 0; while (while (index < notes.size()index < notes.size()) {) { System.out.println (notes.get(index));System.out.println (notes.get(index)); index++;index++; }}} }

Pseudo-code expression of the Pseudo-code expression of the actions of the above while loopactions of the above while loop

(Increment (Increment indexindex by 1) by 1)index = index + 1index = index + 1

private ArrayList<String> notes; private ArrayList<String> notes; // The notebook// The notebook

... other fields, constructor(s), other methods... other fields, constructor(s), other methods

previous previous exampleexample

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

while the iterator says there is another element,do ask the iterator for the next element and print it.

/**/** * List all notes in the notebook.* List all notes in the notebook. */*/public void listNotes()public void listNotes(){{ Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator(); while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next()); }}} }

Pseudo-code expression of the Pseudo-code expression of the actions of the above while loopactions of the above while loop

private ArrayList<String> notes; private ArrayList<String> notes; // The notebook// The notebook

... other fields, constructor(s), other methods... other fields, constructor(s), other methodsEvery Every collectioncollection object has an object has an

IteratorIterator<...><...> object object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")notes.add("...")

notes:ArrayList<String>

:String : String : String : String

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

Iterator<String> it = notes.iterator()Iterator<String> it = notes.iterator()Iterator<String> it = notes.iterator()Iterator<String> it = notes.iterator()

: String : String

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

it.hasNext()it.hasNext()it.hasNext()it.hasNext()

: String : String

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

System.out.println (it.next());System.out.println (it.next());System.out.println (it.next());System.out.println (it.next());

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

tmptmp

it.hasNext()it.hasNext()it.hasNext()it.hasNext() ✔

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

tmptmp

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

it.hasNext()it.hasNext()it.hasNext()it.hasNext() ✔

it:Iterator<String>

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

it:Iterator<String>

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String

it:Iterator<String>

: String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

it.hasNext()it.hasNext()it.hasNext()it.hasNext() ✔

it:Iterator<String>

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

it:Iterator<String>

tmptmp

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp); String tmp = it.next();String tmp = it.next(); System.out.println (tmp);System.out.println (tmp);

tmptmpit:Iterator<String>

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

tmptmpit:Iterator<String>

it.hasNext()it.hasNext()it.hasNext()it.hasNext() ✗

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next());}}

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next());}}

notes:ArrayList<String>

:String : String : String : String

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next());}}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next());}}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next());}}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next());System.out.println (it.next());}}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next()); System.out.println (it.next()); }}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next()); System.out.println (it.next()); }}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next()); System.out.println (it.next()); }}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next()); System.out.println (it.next()); }}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next()); System.out.println (it.next()); }}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

notes:ArrayList<String>

:String : String : String : String

Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator();while (while (it.hasNext()it.hasNext()) {) { System.out.println (it.next()); System.out.println (it.next()); }}

it:Iterator<String>

Reprise .Reprise .....

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

boolean boolean searchingsearching = true; = true;Iterator<ElementType> it = myCollection.iterator();Iterator<ElementType> it = myCollection.iterator();while (while (searchingsearching && && it.hasNext()it.hasNext()) {) { ElementType thing = it.next();ElementType thing = it.next(); ... do something with ... do something with thingthing ... maybe set ... maybe set searchingsearching false false}}

Iterator-whileIterator-while loop patternloop pattern

while we’re still searching and there is more left to search,do consider the next thing in the collection and whether to continue.

construct iteratorconstruct iteratorearly exit conditionearly exit condition

Statements to be repeatedStatements to be repeated

Pseudo-code expression of the actions of this while Pseudo-code expression of the actions of this while looploop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Searching a Collection/**/** * Search all notes in the notebook for the first* Search all notes in the notebook for the first * one containing a specified piece of text. * one containing a specified piece of text. * * * @param searchString The sought text * @param searchString The sought text * @return The note containing the text * @return The note containing the text * (if none found, return null) * (if none found, return null) */*/public String searchNotes2 (String public String searchNotes2 (String searchStringsearchString)){{ ... code body of the method... code body of the method} }

If If nullnull is returned, it means no note containing the search string was is returned, it means no note containing the search string was found.found.If If nullnull is returned, it means no note containing the search string was is returned, it means no note containing the search string was found.found.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public String searchNotes2 (String public String searchNotes2 (String searchStringsearchString)){{ String found = null;String found = null; // so far, not found it// so far, not found it Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator(); while ((while ((found == nullfound == null) && () && (it.hasNext()it.hasNext())) {)) { String note =String note = it.next() it.next();; if (note.contains(searchString)) {if (note.contains(searchString)) { // stop here - we don't need to keep looking.// stop here - we don't need to keep looking. found = note;found = note; }} }} return return foundfound;;}}

Either weEither we foundfound a note containing the search string ... and stopped a note containing the search string ... and stopped searching …searching …Either weEither we foundfound a note containing the search string ... and stopped a note containing the search string ... and stopped searching …searching …

Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and foundfound is still is still nullnull..Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and foundfound is still is still nullnull..

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Either we found a Either we found a notenote containing the search string ... returned it containing the search string ... returned it … exiting the loop and the method immediately. … exiting the loop and the method immediately. Either we found a Either we found a notenote containing the search string ... returned it containing the search string ... returned it … exiting the loop and the method immediately. … exiting the loop and the method immediately.

Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned nullnull..Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned nullnull..

alternative

alternative coding 1

coding 1public String searchNotes2 (String public String searchNotes2 (String searchStringsearchString)){{ Iterator<String> it = notes.iterator();Iterator<String> it = notes.iterator(); while (while (it.hasNext()it.hasNext()) {) { String noteString note = = it.next() it.next();; if (note.contains(searchString)) {if (note.contains(searchString)) { // stop here - we don't need to keep looking.// stop here - we don't need to keep looking. return note;return note; }} }} return return nullnull;;}}

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Either we found a Either we found a notenote containing the search string ... returned it containing the search string ... returned it … exiting the loop and the method immediately. … exiting the loop and the method immediately. Either we found a Either we found a notenote containing the search string ... returned it containing the search string ... returned it … exiting the loop and the method immediately. … exiting the loop and the method immediately.

Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned nullnull..Or we searched the whole collection, didn’t find it andOr we searched the whole collection, didn’t find it and returned returned nullnull..

alternative

alternative coding 2

coding 2public String searchNotes2 (String public String searchNotes2 (String searchStringsearchString)){{ for (for (String note : notesString note : notes) {) { if (note.contains(searchString)) {if (note.contains(searchString)) { // stop here - we don't need to keep looking.// stop here - we don't need to keep looking. return note;return note; }} }} return return nullnull;;}}

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Different Forms of Iteration• Ways to iterate over a collection:Ways to iterate over a collection:

• for-each loopfor-each loop• Use if we want to process every element.Use if we want to process every element.• But we can exit early with a But we can exit early with a returnreturn statement. statement.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

• while loopwhile loop• Need to declare and manage an Need to declare and manage an indexindex variable. variable.• Need not involve a collection.Need not involve a collection.

• Iterator object + while loopIterator object + while loop• Need to declare and manage an Need to declare and manage an iteratoriterator variable. variable.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

• Iteration is an fundamental programming Iteration is an fundamental programming patternpattern..

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• Looking a little deeper:Looking a little deeper:• for-each loopfor-each loop

• Use if we want to process every element.Use if we want to process every element.• But we can exit early with a But we can exit early with a returnreturn statement. statement.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

• Iterator object + while loopIterator object + while loop• Need to declare and manage an Need to declare and manage an iteratoriterator variable. variable.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

For the examples shown, it has always been simpler to code For the examples shown, it has always been simpler to code with a with a for-each loopfor-each loop, rather than an , rather than an iterator-whileiterator-while loop.loop.For the examples shown, it has always been simpler to code For the examples shown, it has always been simpler to code with a with a for-each loopfor-each loop, rather than an , rather than an iterator-whileiterator-while loop.loop.

Different Forms of Iteration

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• Looking a little deeper:Looking a little deeper:• for-each loopfor-each loop

• Use if we want to process every element.Use if we want to process every element.• But we can exit early with a But we can exit early with a returnreturn statement. statement.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

• Iterator object + while loopIterator object + while loop• Need to declare and manage an Need to declare and manage an iteratoriterator variable. variable.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

For the examples shown, it has always been simpler to code For the examples shown, it has always been simpler to code with a with a for-each loopfor-each loop, rather than an , rather than an iterator-whileiterator-while loop.loop.For the examples shown, it has always been simpler to code For the examples shown, it has always been simpler to code with a with a for-each loopfor-each loop, rather than an , rather than an iterator-whileiterator-while loop.loop.

With an With an IteratorIterator, however, we can , however, we can removeremove elements from a elements from a collection – we can’t do that with a collection – we can’t do that with a for-each loopfor-each loop..

With an With an IteratorIterator, however, we can , however, we can removeremove elements from a elements from a collection – we can’t do that with a collection – we can’t do that with a for-each loopfor-each loop..

Different Forms of Iteration

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

With an With an IteratorIterator, however, we can , however, we can removeremove elements from a elements from a collection – we can’t do that with a collection – we can’t do that with a for-each loopfor-each loop..

With an With an IteratorIterator, however, we can , however, we can removeremove elements from a elements from a collection – we can’t do that with a collection – we can’t do that with a for-each loopfor-each loop..

• Looking a little deeper:Looking a little deeper:• for-each loopfor-each loop

• Use if we want to process every element.Use if we want to process every element.• But we can exit early with a But we can exit early with a returnreturn statement. statement.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

• Iterator object + while loopIterator object + while loop• Need to declare and manage an Need to declare and manage an iteratoriterator variable. variable.• Often used with a collection where Often used with a collection where indexedindexed access access

(e.g. (e.g. get(index)get(index)) is inefficient … or impossible.) is inefficient … or impossible.

If we need to iterate through If we need to iterate through two (or more) collection objects in the two (or more) collection objects in the same loopsame loop, we have to use , we have to use a a two (or more)two (or more) iterator-whileiterator-while

loop.loop.

If we need to iterate through If we need to iterate through two (or more) collection objects in the two (or more) collection objects in the same loopsame loop, we have to use , we have to use a a two (or more)two (or more) iterator-whileiterator-while

loop.loop.

Different Forms of Iteration

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The auction Project

• The auction project provides further illustration of collections and iteration.

• One further point to follow up is the nullnull value:

• Used to indicate: there is no objectthere is no object.

• We can test if an object variable holds the nullnull value:

• We can make a object variable hold the nullnull value:

if (if (xx ==== nullnull) {...}) {...}if (if (xx ==== nullnull) {...}) {...}

xx == nullnull;;xx == nullnull;;

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Review• Loop statements allow a block of statements Loop statements allow a block of statements

to be repeated.to be repeated.

• The The for-eachfor-each loop allows iteration loop allows iteration over a over a whole collection whole collection – but you can exit early with – but you can exit early with a a returnreturn. .

• The The whilewhile loop allows the repetition to be loop allows the repetition to be controlled by a controlled by a boolean expressionboolean expression..

• A special A special IteratorIterator object can be obtained object can be obtained from any collection object:from any collection object:

• Used with a Used with a whilewhile loop, this provides sequential loop, this provides sequential iteration through iteration through the whole (or initial part of the)the whole (or initial part of the) collection.collection.