1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each PROS easy to use access to ALL items one-by-one ability to change the state.

Slides:



Advertisements
Similar presentations
1 Features of the collection It increases its capacity as necessary. It keeps a private count: –size() accessor. It keeps the objects in order. Details.
Advertisements

Grouping objects Introduction to collections 5.0.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Using Collections. Review of Collections Using an ArrayList It increases its capacity as necessary. It keeps a private count ( size() accessor). It keeps.
Grouping Objects 3 Iterators, collections and the while loop.
Chapter 5: Loops and Files.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Grouping objects Introduction to collections 5.0.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Introduction to Java Java Translation Program Structure
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection.
Grouping objects Introduction to collections 5.0.
1 COS 260 DAY 7 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz next class (September 28) –Chap 3 concepts Assignment 1 Corrected Assignment 2 posted.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Grouping objects Introduction to collections 6.0.
Functional Processing of Collections (Advanced) 6.0.
Chapter 8: Understanding Collections Textbook: Chapter 4.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
for-each PROS CONS easy to use access to ALL items one-by-one
Objects First with Java CITS1001 week 4
Chapter 10 Programming Fundamentals with JavaScript
REPETITION CONTROL STRUCTURE
Objects First with Java Introduction to collections
The switch Statement, and Introduction to Looping
Programming Logic and Design Fourth Edition, Comprehensive
Loop Structures.
Coding #1 if(!(index < 0 || index >= list.size( )-1))
COS 260 DAY 7 Tony Gauvin.
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Loops and Files.
Functional Processing of Collections (Advanced)
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
CSS 161: Fundamentals of Computing
COS 260 DAY 9 Tony Gauvin.
More sophisticated behavior
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Objects First with Java Introduction to collections
Chapter 3 Introduction to Classes, Objects Methods and Strings
COS 260 DAY 10 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
Objects First with Java Introduction to collections
Do … Loop Until (condition is true)
Introduction to Problem Solving and Control Statements
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Collections and iterators
COS 260 DAY 4 Tony Gauvin.
Fundaments of Game Design
Collections and iterators
Presentation transcript:

1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each PROS easy to use access to ALL items one-by-one ability to change the state of the item terminates automatically selective filter using if-else statements actions in body may be complicated with multiple lines use on ANY type of collection abstraction from details of how handling occurs CONS no index provided can NOT stop during looping definite iteration of ALL items can NOT remove or add elements during loop use for collections only access must be to ALL items in sequence [0 to size-1]

Grouping objects Indefinite iteration - the while loop

3 Main concepts to be covered © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. The difference between iterations: –definite … size –indefinite (unbounded) … 0 - infinite The while loop

4 Search tasks are indefinite Consider: searching for your keys You cannot predict, in advance, how many places you will have to look There may be an absolute limit –i.e. check EVERY possible location Or, it may not be any at all –i.e. check 0 locations (you had them!) You will stop when you find them Infinite loops are also possible –Through error or the nature of the task. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

5 The while loop A for-each loop repeats the loop body for every object in a collection –Sometimes we require more flexibility –The while loop supports flexibility We use a boolean condition to decide whether or not to keep iterating Maybe NO need to search to the end This is a very flexible approach Not tied to collections © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

6 While loop pseudo code © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. while(loop condition) { loop body } while we wish to continue, do the things in the loop body boolean test (true or false) while keyword Pseudo-code expression of the actions of a while loop General form of a while loop Statements to be repeated

7 Looking for your keys © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. while(the keys are missing) { look in the next place; } while(not (the keys have been found)) { look in the next place; } while(true) while(!(false))

8 Looking for your keys © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. boolean searching = true; while(searching) { if(they are in the next place) { searching = false; } Suppose we don’t find them? Infinite loop

9 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each == while public void listAllFiles() { int index = 0; while(index < files.size()) { String filename = files.get(index); System.out.println(filename); index++; } Increment index by 1 while the value of index is less than the size of the collection, get and print the next file name, and then increment index public void listAllFiles() { for(String filename : files) { System.out.println(filename); }

10 Elements of the loop We have declared an index variable The condition must be expressed correctly We have to fetch each element The index variable must be incremented explicitly © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

11 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. while loop search PROS can stop at any time during looping indefinite iteration of SOME items using loop condition may change collection during loop use explicit index variable inside and outside of loop index variable records location of item at all times CONS more effort to code requires index looping variable declaration maintain looping variable and manually increment correctly determine loop condition for termination must.get item using index to access the item NOT guaranteed to stop with possible infinite loop

12 for-each versus while © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each –easier to write –safer because it is guaranteed to stop –access is handled for you Access ALL items without changing collection while –don’t have to process entire collection –doesn’t have to be used with a collection –take care to watch for an infinite loop Access only SOME items, includes a record of the index location, and also could be used for non-collections

13 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. Searching a collection A re-occurring fundamental activity Applicable beyond collections Indefinite iteration because we don’t know exactly where to look We must code for both success (stops midway) and failure (after all searched) using an exhausted search Either MUST make the loop condition false to terminate the loop Even works if collection is empty

14 Finishing a search © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. So when do we finish a search? No more items to check: index >= files.size() OR Item has been found: found == true found ! searching

15 Continuing a search We need to state the condition for continuing: So the loop’s condition will be the opposite of that for finishing: index < files.size() && ! found index < files.size() && searching NB: ‘or’ becomes ‘and’ when inverting everything. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

16 Search condition >= becomes < FINISH search when: No more items OR Item is found index >= files.size() || found CONTINUE search while: Still more items AND Item is not found index < files.size() && !found

17 Search condition >= becomes < FINISH search when: No more items OR Item is found index >= files.size() || found CONTINUE search while: Still more items AND Item is not found index < files.size() && !found

18 Search condition OR becomes AND FINISH search when: No more items OR Item is found index >= files.size() || found CONTINUE search while: Still more items AND Item is not found index < files.size() && !found

19 Search condition OR becomes AND FINISH search when: No more items OR Item is found index >= files.size() || found CONTINUE search while: Still more items AND Item is not found index < files.size() && !found

20 Search condition true becomes !true FINISH search when: No more items OR Item is found index >= files.size() || found CONTINUE search while: Still more items AND Item is not found index < files.size() && ! found

21 Search condition true becomes !true FINISH search when: No more items OR Item is found index >= files.size() || found CONTINUE search while: Still more items AND Item is not found index < files.size() && ! found

22 Searching a collection (using searching) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. int index = 0; boolean searching = true; while(index < files.size() && searching) { String file = files.get(index); if(file.equals(searchString)) { // We don't need to keep looking. searching = false; } else { index++; } // Either we found it at index, // or we searched the whole collection.

23 Searching a collection (using found) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. int index = 0; boolean found = false; while(index < files.size() && !found) { String file = files.get(index); if(file.equals(searchString)) { // We don't need to keep looking. found = true; } else { index++; } // Either we found it at index, // or we searched the whole collection.

24 Method findFirst public int findFirst(String searchString) { int index = 0; boolean searching = true; while(searching && index < files.size()) { String filename = files.get(index); if(filename.contains(searchString)) { // Match found searching = false; // Stop searching } else // Not found here {// Keep searching index++;// Move to next item } if(searching) // NO match found { return -1;// Return out-of-bounds } // index for failures else {// Return item index of return index; // where it is found }

25 Indefinite iteration © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. Does the search still work if the collection is empty (but not null)? –Yes! The loop’s body would NOT be entered in that case. Important feature of while: –The body of the while could be executed zero or more times.

26 While with non-collections // Print all even numbers from 2 to 30 int index = 2; while(index <= 30) { System.out.println(index); index = index + 2; } NOTE: This while loop uses definite iteration, since it is clear from the start exactly how many times the loop will be repeated. But, we could NOT have used a for-each loop, because there is no collection of items. local variable START: index start STOP: index end increment

27 The String class The String class is defined in the java.lang package It has some special features that need a little care In particular, comparison of String objects can be tricky

28 String equality if(input == "bye") {... } if(input.equals("bye")) {... } Important: Always use.equals to test String equality! © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. tests identitytests equality Do not use!!

29 Identity vs equality 1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. Other (non-String) objects: person1 == person2 ? “Fred” :Person person1person2 “Jill” :Person false

30 Identity vs equality 2 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. Other (non-String) objects: person1 == person2 ? “Fred” :Person person1person2 “Fred” :Person false same value

31 Identity vs equality 3 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. Other (non-String) objects: person1 == person2 ? “Fred” :Person person1person2 “Fred” :Person true

32 Identity vs equality (Strings) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. "bye" :String input "bye" :String String input = reader.getInput(); if(input == "bye") {... } == ? false! == tests identity

33 Identity vs equality (Strings) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. "bye" :String input "bye" :String String input = reader.getInput(); if(input.equals("bye")) {... }.equals ? true! equals tests equality

34 The problem with Strings The compiler merges identical String literals in the program code –The result is reference equality for apparently distinct String objects But this cannot be done for identical strings that arise outside the program’s code –e.g. from user input

35 Moving away from String © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. Our collection of String objects for music tracks is limited private ArrayList tracks; No separate id for artist, title, etc… Make Track class with separate fields private String artist; private String title; private String filename; Changes collection of music tracks private ArrayList tracks;

36 ArrayList of non-String objects public class MusicOrganizer { // ArrayList of Track objects private ArrayList tracks; : } // non-String Track class definition public class Track { private String artist; private String title; private String filename; : }

37 Class diagram public class MusicOrganizer { private ArrayList tracks; : } public class Track { private String artist; private String title; private String filename; : } MusicOrganizer Track uses or references

38 Object diagram Suppose the project consists of the following: 1 object instance of the MusicOrganizer class named myMusic 2 instances of Track items in the tracks ArrayList field of myMusic new Track(“Maroon 5”, “Payphone”, “payphone.mp3”) new Track(“MTKO”, “Classic”, “classic.mp3”) myMusic: MusicOrganizer tracks :ArrayList 0 1 :Track artist title filename :String “Maroon 5” :String “Payphone” :String “payphone.mp3” :Track artist title filename :String “MTKO” :String “Classic” :String “classic.mp3”