0% found this document useful (0 votes)
3 views30 pages

CPSC 2231_Chapter 4_Week 3

The document provides a comprehensive overview of looping constructs in programming, specifically focusing on for loops, while loops, and iterators for iterating over collections. It explains the mechanics of each loop type, their appropriate use cases, and how to remove elements from collections using iterators. Additionally, it introduces concepts related to an auction project, including object handling, method chaining, and the upcoming midterm exam details.

Uploaded by

webadatoru-2335
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views30 pages

CPSC 2231_Chapter 4_Week 3

The document provides a comprehensive overview of looping constructs in programming, specifically focusing on for loops, while loops, and iterators for iterating over collections. It explains the mechanics of each loop type, their appropriate use cases, and how to remove elements from collections using iterators. Additionally, it introduces concepts related to an auction project, including object handling, method chaining, and the upcoming midterm exam details.

Uploaded by

webadatoru-2335
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

CPSC 2231

Programming Workshop
Fall, 2024

School of Engineering & Computing– Computer Science Department


Dr. Haolin Tang

1
Review: For loop vs For-each loop
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

for (int i = 2; i <=10; i++) {


System.out.println(i);
}

for (type variableName : arrayName) { // code block to be executed }

String[] cars = {"Volvo", "BMW", "Ford"};


for (String brand : cars) {
System.out.println(brand);
}

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. 2


Review: While with collections
/**
* List all file names in the organizer.
*/
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

3
Grouping objects

Iterator objects

4
Iterator type

• Third variation to iterate over a collection


• Uses a while loop and Iterator object
• But NO integer index variable
• Takes advantage of abstraction with use
of library class import java.util.Iterator;

5
Iterator vs iterator()

• Collections (e.g. ArrayList) have an


iterator() method.
• This returns an Iterator object.
• Iterator<E> has methods:
– boolean hasNext()
– E next()
– void remove()

6
Using an Iterator object
returns an Iterator object
java.util.Iterator

Iterator<ElementType> it = myCollection.iterator();
while(it.hasNext()) {
call it.next() to get the next object
do something with that object
}

• Declare variable it as type Iterator of ElementType


• Use iterator() method of collection (e.g. ArrayList) and
assign the returned Iterator object to variable it
• it.hasNext() returns true if the iterations has more elements
• it.next() will return the next element in the iteration

© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. 7


Iterator object example
java.util.Iterator returns an Iterator object

public void listAllFiles()


{
Iterator<Track> it = files.iterator();
while(it.hasNext()) {
Track tk = it.next();
System.out.println(tk.getDetails());
}
}
• Prints ALL tracks in the collection (like while & for-each)
• Still use while … BUT do not need an index variable
• Iterator keeps track of current location, if there are any more
items (hasNext) and which one to return (next)
• Iterator.next returns next item AND moves past that item
(can NOT go back)
8
Iterator mechanics

9
myList:List
myList.iterator()

:Element :Element :Element :Element

:Iterator

10
myList:List

:Element :Element :Element :Element

:Iterator:Iterator

hasNext()?
next()

Element e = iterator.next();

11
myList:List

:Element :Element :Element :Element

:Iterator :Iterator

hasNext()?
next()

12
myList:List

:Element :Element :Element :Element

:Iterator :Iterator

hasNext()?
next()

13
myList:List

:Element :Element :Element :Element

:Iterator :Iterator

hasNext()?
next()

14
myList:List

:Element :Element :Element :Element

:Iterator

hasNext()? ✗

15
Index versus Iterator
• Ways to iterate over a collection:
– for-each loop.
• Use if we want to process every element.
– while loop.
• Use if we might want to stop part way through.
• Use for repetition that doesn't involve a collection.
– Iterator object.
• Use if we might want to stop part way through.
• Often used with collections where indexed access is not
very efficient, or impossible.
• Use to remove from a collection.
• Iteration is an important programming pattern.

16
Removing from a collection
Iterator<Track> it = tracks.iterator();
while(it.hasNext()) {
Track t = it.next();
String artist = t.getArtist();
if(artist.equals(artistToRemove)) {
it.remove();
}
}

Using the Iterator’s remove method.

17
Removing from a collection –
wrong!
int index = 0;
while(index < tracks.size()) {
Track t = tracks.get(index);
String artist = t.getArtist();
if(artist.equals(artistToRemove)) {
tracks.remove(index);
}
index++;
}
Can you spot what is wrong?
18
Review
• Loop statements allow a block of statements to be
repeated.
• The for-each loop allows iteration over a whole
collection.
• The while loop allows the repetition to be controlled
by a boolean expression.
• All collection classes provide special Iterator
objects that provide sequential access to a whole
collection.

19
The auction project
• The auction project provides further
illustration of collections and iteration.
• Examples of using null.
• Anonymous objects.
• Chaining method calls.

20
The auction project

21
auction project
Online Auction system:
•Sell items via enterLot with String description
•Auction object creates Lot object for entered lot
• lot number and description is assigned with no bidders
•Bidder Person can register with only their name
•Place bid with bidFor method of Auction object
with lot number and how much to bid
• Lot number passed so Lot objects internal to Auction
•Auction object transforms bid amount to object
•Lot records the highest bid object
© 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. 22
null

• Used with object types.


• Used to indicate, 'no object'.
• We can test if an object variable holds the
null value:

if(highestBid == null) …

• Used to indicate ‘no bid yet’.

23
Anonymous objects
• Objects are often created and handed on
elsewhere immediately:

Lot furtherLot = new Lot(…);


lots.add(furtherLot);

• We don’t really need furtherLot:

lots.add(new Lot(…));

24
Chaining method calls
• Methods often return objects.
• We often immediately call a method on the
returned object.
Bid bid = lot.getHighestBid();
Person bidder = bid.getBidder();
• We can use the anonymous object concept
and chain method calls:
lot.getHighestBid().getBidder()

25
Chaining method calls
• Each method in the chain is called on the
object returned from the previous method call
in the chain.
String name =
lot.getHighestBid().getBidder().getName();

Returns a Bid object from the Lot

Returns a Person object from the Bid

Returns a String object from the Person

26
Review
• Collections are used widely in many different
applications.
• The Java library provides many different
‘ready made’ collection classes.
• Collections are often manipulated using
iterative control structures.
• The while loop is the most important control
structure to master.

27
Review
• Some collections lend themselves to index-
based access; e.g. ArrayList.
• Iterator provides a versatile means to
iterate over different types of collection.
• Removal using an Iterator is less error-
prone in some circumstance.

28
Midterm Exam
• Midterm exam is scheduled on 10/17, Thursday.

• It will cover all topics in the lecture slides.

• It will consist of theoretical problems and one


coding project.

29
Thank you

Are there any questions?


Email: htang@fairfield.edu

30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy