SlideShare a Scribd company logo
1
 To understand the iterator concept and its types.
 To differentiate between index access and Iterators
 To present which loop structure is used to remove elements from the
collection.
 To implement a music-organizer project.
 To implement an auction system example.
 To describe why arrays are necessary in programming.
 To illustrate array reference variables and create arrays.
 To initialize the values in an array.
 To access array elements using indexed variables.
 To declare, create, and initialize an array using an array initializer.
 To illustrate how for loop is working.
2
 An iterator is an object that provides functionality to iterate over all
elements of a collection.
 Iteration is a vital tool in almost every programming project
 Iterator (note the uppercase I) is a Java type, but we will also
encounter a method called iterator (lowercase i).
 Collections; like ArrayList, have a iterator() method.
 The iterator method of ArrayList returns an Iterator object.
3
 Iterator is also defined in the java.util package, so we must add a
second import statement to the class file to use it:
import java.util.ArrayList;
import java.util.Iterator;
 An Iterator provides just three methods, and two of these are used
to iterate over a collection: hasNext and next.
 Neither takes a parameter, but both have non-void return types, so
they are used in expressions.
4
 The way we usually use an Iterator can be described in pseudo-
code as follows:
5
 One of the keys to understanding how Iterator works is that the call
to Next causes the Iterator to return the next item in the collection
and then move past that item.
 Therefore, successive calls to next on an Iterator will always return
distinct items.
 The Iterator reaches the end of the collection and then returns false
from a call to hasNext.
 Once hasNext has returned false, it would be an error to try to call
next on that particular Iterator object.
6
 We have at least three different ways in which we can iterate over
an ArrayList. We can use:
◦ a for-each loop
◦ the get method with an integer index variable, while loop
◦ an Iterator object
 All approaches seem about equal in quality.
 Iteration is an important programming pattern.
7
 For-each loop is:
◦ slightly easier to understand, but the least flexible.
◦ used if all elements of a collection are to be processed (i.e., definite iteration).
 While loop is:
◦ iteration can more easily be stopped in the middle of processing (indefinite
iteration),
◦ preferable when processing only a part of the collection.
◦ used for repetition that doesn't involve a collection.
 Iterator object:
◦ Iteration can more easily be stopped in the middle of processing (indefinite
iteration),
◦ Preferable when processing only a part of the collection.
◦ Often used with collections where indexed access is not very efficient, or
impossible.
◦ Used to remove from a collection.
8
 We need to think which looping structure to use when we have to
remove elements from the collection while iterating.
 The proper solution to removing while iterating is to use an Iterator.
 Its third method (in addition to hasNext and next) is remove.
 It takes no parameter and has a void return type.
 Calling remove will remove the item that was returned by the most
recent call to next.
9
 Here is some sample code. Note that we do not use the tracks collection
variable in the body of the loop.
 While both ArrayList and Iterator have remove methods, we must use the
Iterator’s remove method, not the ArrayList’s.
10
 In music-organizer Project we have seen:
◦ we can use an ArrayList object, created from a class out of the class
library, to store an arbitrary number of objects in a collection.
◦ we can use a loop to iterate over all elements in the collection.
◦ With an ArrayList, we can access elements either by index or we can
iterate over all elements using an Iterator object.
11
 The auction project models part of the operation of an online auction
system. The idea is that an auction consists of a set of items offered
for sale. These items are called “lots”, and each is assigned a
unique lot number by the program. A person can try to buy a lot
they want by bidding an amount of money for it.
 The class structure of the auction project contains the following
classes: Auction, Bid, Lot, and Person.
12
 If a data field of a reference type does not reference any object, the
data field holds a special literal value, null.
 So null is a value for the field that makes it clear that there is
currently “no object” being referred to by that variable.
 If a variable contains the null value, a method call should not be
made on it.
 We sometimes have to use an if statement to test whether a
variable contains null or not before calling a method on that variable.
 Example:
if(highestBid == null) …
13
 The Lot class stores a description of the lot, a lot number, and
details of the highest bid received for it so far. The most complex
part of the class is the bidFor method.
14
15
16
17
 Objects are often created and handed on elsewhere immediately.
The following code is doing two things:
◦ We are creating a new Lot object.
◦ We are also passing this new object to the ArrayList’s add method.
Lot furtherLot = new Lot(…);
lots.add(furtherLot);
 Alternate way (We don’t really need furtherLot):
lots.add(new Lot(nextLotNumber, description));
18
 Methods often return objects.
 We often immediately call a method on the returned object.
Bid bid = lot.getHighestBid();
Person bidder = bid.getBidder();
 Each method in the chain is called on the object returned from the
previous method call in the chain.
19
 We can use the anonymous object concept and chain method calls:
lot.getHighestBid().getBidder()
 The call to getHighestBid returns an anonymous Bid object, and the
getBidder method is then called on that object.
20
 A special fixed-size collection type is available: an array.
 Array is a data structure that represents a collection of the same
types of data.
 Array advantages over the flexible-size collection classes:
◦ Access to the items held in an array is often more efficient than access
to the items in a comparable flexible-size collection.
◦ Arrays are able to store either objects or primitive-type values. Flexible-
size collections can store only objects.
 Arrays use a special syntax.
21
 Following picture represents array myList. Here, myList holds ten
double values and the indices are from 0 to 9.
22
 Square-bracket notation is used to access an array element:
hourCounts[...]
 Elements are used like ordinary variables.
 The target of an assignment:
hourCounts[hour] = ...;
 datatype[] arrayRefVar = new datatype[arraySize];
double[] myArray = new double[20];
 datatype arrayRefVar[] = new datatype[arraySize];
double myArray[] = new double[20];
23
24
 Once an array is created, its size is fixed. It cannot be changed.
 You can find its size using
arrayRefVar.length
 For example,
myArray.length returns 20
25
 The following example shows the declaration, creation, and
initialization of an array:
double[] myArray = {1.9, 2.9, 3.4, 3.5};
 This shorthand notation is equivalent to the following statements:
double[] myArray = new double[4];
myArray[0] = 1.9;
myArray[1] = 2.9;
myArray[2] = 3.4;
myArray[3] = 3.5;
26
declaration,
creation and
initialization
27
 How an array variable is associated with an array object ?
 An array of 24 integers presented in the following figure:
28
29
 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.
 We presented Flexible Collection like ArrayList. Classes such as ArrayList
conveniently allow us to create collections containing an arbitrary number of objects.
 Arrays are appropriate where a fixed-size collection is required.
 Arrays use a special syntax.
 For loops are used when an index variable is required.
 For loops offer an alternative to while loops when the number of repetitions is known.
 Used with a regular step size.
30
 Barnes, David J., and Kölling, Michael. 2012. Objects First with
Java, A practical Introduction Using BlueJ (5th Edition). Boston:
Preston.
 Liang, Y. Daniel. 2011. Introduction to Java Programming,
Comprehensive (8th Ed.) Prentice Hall.
 http://www.tutorialspoint.com/java/java_decision_making.htm
 http://www.homeandlearn.co.uk/java/java.html
31

More Related Content

PDF
An Introduction to Programming in Java: Arrays
Martin Chapman
 
PPTX
Array in C# 3.5
Gopal Ji Singh
 
PPT
Array in Java
Shehrevar Davierwala
 
PDF
Java Arrays
OXUS 20
 
PPTX
7array in c#
Sireesh K
 
PPTX
Arrays in Java
Abhilash Nair
 
PPTX
Array lecture
Joan Saño
 
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Array in C# 3.5
Gopal Ji Singh
 
Array in Java
Shehrevar Davierwala
 
Java Arrays
OXUS 20
 
7array in c#
Sireesh K
 
Arrays in Java
Abhilash Nair
 
Array lecture
Joan Saño
 

What's hot (20)

PPTX
Arrays C#
Raghuveer Guthikonda
 
PPTX
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
PDF
C++ Standard Template Library
Ilio Catallo
 
PDF
Array data structure
maamir farooq
 
PPTX
C# Arrays
Hock Leng PUAH
 
PPTX
Lecture11 standard template-library
Hariz Mustafa
 
PPTX
Java arrays
Jin Castor
 
PPT
Java: Introduction to Arrays
Tareq Hasan
 
PPT
Java10 Collections and Information
SoftNutx
 
PPTX
Python array
Arnab Chakraborty
 
DOC
Array properties
Shravan Sharma
 
PPT
L11 array list
teach4uin
 
PDF
Scala Collections : Java 8 on Steroids
François Garillot
 
PPTX
Collections
sagsharma
 
PPTX
Arrays in programming
TaseerRao
 
PPT
Lec 25 - arrays-strings
Princess Sam
 
PPTX
Array ppt
Kaushal Mehta
 
PPTX
Data structures in c#
SivaSankar Gorantla
 
PPTX
Lecture05 operator overloading-and_exception_handling
Hariz Mustafa
 
PPTX
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
C++ Standard Template Library
Ilio Catallo
 
Array data structure
maamir farooq
 
C# Arrays
Hock Leng PUAH
 
Lecture11 standard template-library
Hariz Mustafa
 
Java arrays
Jin Castor
 
Java: Introduction to Arrays
Tareq Hasan
 
Java10 Collections and Information
SoftNutx
 
Python array
Arnab Chakraborty
 
Array properties
Shravan Sharma
 
L11 array list
teach4uin
 
Scala Collections : Java 8 on Steroids
François Garillot
 
Collections
sagsharma
 
Arrays in programming
TaseerRao
 
Lec 25 - arrays-strings
Princess Sam
 
Array ppt
Kaushal Mehta
 
Data structures in c#
SivaSankar Gorantla
 
Lecture05 operator overloading-and_exception_handling
Hariz Mustafa
 
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Ad

Similar to Lecture 7- Iterator and for loop over arrays (20)

PDF
Lecture 4 - Object Interaction and Collections
Syed Afaq Shah MACS CP
 
PPT
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
PDF
javacollections.pdf
ManojKandhasamy1
 
PPTX
Lecture 9
talha ijaz
 
PPT
Collection Framework.power point presentation.......
Betty333100
 
PDF
Lecture 5 - Interaction with for each and while loops
Syed Afaq Shah MACS CP
 
PDF
Lecture 8 Library classes
Syed Afaq Shah MACS CP
 
PPT
22.ppt
BharaniDaran15
 
PPTX
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
PPT
description of Collections, seaching & Sorting
mdimberu
 
PPTX
ch 7 single dimension array in oop .pptx
nilampatoliya
 
PPT
Java collection
Arati Gadgil
 
PPTX
collection framework.pptx
SoniaKapoor56
 
PPTX
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
PPTX
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
PPTX
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
PPTX
VTUOOPMCA5THMODULECollection OverVi.pptx
VeenaNaik23
 
PPTX
Java Unit 2 (Part 2)
Dr. SURBHI SAROHA
 
PPTX
List interface in collections framework
Ravi Chythanya
 
PPTX
oop lecture framework,list,maps,collection
ssuseredfbe9
 
Lecture 4 - Object Interaction and Collections
Syed Afaq Shah MACS CP
 
javacollections.pdf
ManojKandhasamy1
 
Lecture 9
talha ijaz
 
Collection Framework.power point presentation.......
Betty333100
 
Lecture 5 - Interaction with for each and while loops
Syed Afaq Shah MACS CP
 
Lecture 8 Library classes
Syed Afaq Shah MACS CP
 
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
description of Collections, seaching & Sorting
mdimberu
 
ch 7 single dimension array in oop .pptx
nilampatoliya
 
Java collection
Arati Gadgil
 
collection framework.pptx
SoniaKapoor56
 
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULECollection OverVi.pptx
VeenaNaik23
 
Java Unit 2 (Part 2)
Dr. SURBHI SAROHA
 
List interface in collections framework
Ravi Chythanya
 
oop lecture framework,list,maps,collection
ssuseredfbe9
 
Ad

Recently uploaded (20)

PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Exploring AI Agents in Process Industries
amoreira6
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
Activate_Methodology_Summary presentatio
annapureddyn
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 

Lecture 7- Iterator and for loop over arrays

  • 1. 1
  • 2.  To understand the iterator concept and its types.  To differentiate between index access and Iterators  To present which loop structure is used to remove elements from the collection.  To implement a music-organizer project.  To implement an auction system example.  To describe why arrays are necessary in programming.  To illustrate array reference variables and create arrays.  To initialize the values in an array.  To access array elements using indexed variables.  To declare, create, and initialize an array using an array initializer.  To illustrate how for loop is working. 2
  • 3.  An iterator is an object that provides functionality to iterate over all elements of a collection.  Iteration is a vital tool in almost every programming project  Iterator (note the uppercase I) is a Java type, but we will also encounter a method called iterator (lowercase i).  Collections; like ArrayList, have a iterator() method.  The iterator method of ArrayList returns an Iterator object. 3
  • 4.  Iterator is also defined in the java.util package, so we must add a second import statement to the class file to use it: import java.util.ArrayList; import java.util.Iterator;  An Iterator provides just three methods, and two of these are used to iterate over a collection: hasNext and next.  Neither takes a parameter, but both have non-void return types, so they are used in expressions. 4
  • 5.  The way we usually use an Iterator can be described in pseudo- code as follows: 5
  • 6.  One of the keys to understanding how Iterator works is that the call to Next causes the Iterator to return the next item in the collection and then move past that item.  Therefore, successive calls to next on an Iterator will always return distinct items.  The Iterator reaches the end of the collection and then returns false from a call to hasNext.  Once hasNext has returned false, it would be an error to try to call next on that particular Iterator object. 6
  • 7.  We have at least three different ways in which we can iterate over an ArrayList. We can use: ◦ a for-each loop ◦ the get method with an integer index variable, while loop ◦ an Iterator object  All approaches seem about equal in quality.  Iteration is an important programming pattern. 7
  • 8.  For-each loop is: ◦ slightly easier to understand, but the least flexible. ◦ used if all elements of a collection are to be processed (i.e., definite iteration).  While loop is: ◦ iteration can more easily be stopped in the middle of processing (indefinite iteration), ◦ preferable when processing only a part of the collection. ◦ used for repetition that doesn't involve a collection.  Iterator object: ◦ Iteration can more easily be stopped in the middle of processing (indefinite iteration), ◦ Preferable when processing only a part of the collection. ◦ Often used with collections where indexed access is not very efficient, or impossible. ◦ Used to remove from a collection. 8
  • 9.  We need to think which looping structure to use when we have to remove elements from the collection while iterating.  The proper solution to removing while iterating is to use an Iterator.  Its third method (in addition to hasNext and next) is remove.  It takes no parameter and has a void return type.  Calling remove will remove the item that was returned by the most recent call to next. 9
  • 10.  Here is some sample code. Note that we do not use the tracks collection variable in the body of the loop.  While both ArrayList and Iterator have remove methods, we must use the Iterator’s remove method, not the ArrayList’s. 10
  • 11.  In music-organizer Project we have seen: ◦ we can use an ArrayList object, created from a class out of the class library, to store an arbitrary number of objects in a collection. ◦ we can use a loop to iterate over all elements in the collection. ◦ With an ArrayList, we can access elements either by index or we can iterate over all elements using an Iterator object. 11
  • 12.  The auction project models part of the operation of an online auction system. The idea is that an auction consists of a set of items offered for sale. These items are called “lots”, and each is assigned a unique lot number by the program. A person can try to buy a lot they want by bidding an amount of money for it.  The class structure of the auction project contains the following classes: Auction, Bid, Lot, and Person. 12
  • 13.  If a data field of a reference type does not reference any object, the data field holds a special literal value, null.  So null is a value for the field that makes it clear that there is currently “no object” being referred to by that variable.  If a variable contains the null value, a method call should not be made on it.  We sometimes have to use an if statement to test whether a variable contains null or not before calling a method on that variable.  Example: if(highestBid == null) … 13
  • 14.  The Lot class stores a description of the lot, a lot number, and details of the highest bid received for it so far. The most complex part of the class is the bidFor method. 14
  • 15. 15
  • 16. 16
  • 17. 17
  • 18.  Objects are often created and handed on elsewhere immediately. The following code is doing two things: ◦ We are creating a new Lot object. ◦ We are also passing this new object to the ArrayList’s add method. Lot furtherLot = new Lot(…); lots.add(furtherLot);  Alternate way (We don’t really need furtherLot): lots.add(new Lot(nextLotNumber, description)); 18
  • 19.  Methods often return objects.  We often immediately call a method on the returned object. Bid bid = lot.getHighestBid(); Person bidder = bid.getBidder();  Each method in the chain is called on the object returned from the previous method call in the chain. 19
  • 20.  We can use the anonymous object concept and chain method calls: lot.getHighestBid().getBidder()  The call to getHighestBid returns an anonymous Bid object, and the getBidder method is then called on that object. 20
  • 21.  A special fixed-size collection type is available: an array.  Array is a data structure that represents a collection of the same types of data.  Array advantages over the flexible-size collection classes: ◦ Access to the items held in an array is often more efficient than access to the items in a comparable flexible-size collection. ◦ Arrays are able to store either objects or primitive-type values. Flexible- size collections can store only objects.  Arrays use a special syntax. 21
  • 22.  Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9. 22
  • 23.  Square-bracket notation is used to access an array element: hourCounts[...]  Elements are used like ordinary variables.  The target of an assignment: hourCounts[hour] = ...;  datatype[] arrayRefVar = new datatype[arraySize]; double[] myArray = new double[20];  datatype arrayRefVar[] = new datatype[arraySize]; double myArray[] = new double[20]; 23
  • 24. 24
  • 25.  Once an array is created, its size is fixed. It cannot be changed.  You can find its size using arrayRefVar.length  For example, myArray.length returns 20 25
  • 26.  The following example shows the declaration, creation, and initialization of an array: double[] myArray = {1.9, 2.9, 3.4, 3.5};  This shorthand notation is equivalent to the following statements: double[] myArray = new double[4]; myArray[0] = 1.9; myArray[1] = 2.9; myArray[2] = 3.4; myArray[3] = 3.5; 26 declaration, creation and initialization
  • 27. 27
  • 28.  How an array variable is associated with an array object ?  An array of 24 integers presented in the following figure: 28
  • 29. 29
  • 30.  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.  We presented Flexible Collection like ArrayList. Classes such as ArrayList conveniently allow us to create collections containing an arbitrary number of objects.  Arrays are appropriate where a fixed-size collection is required.  Arrays use a special syntax.  For loops are used when an index variable is required.  For loops offer an alternative to while loops when the number of repetitions is known.  Used with a regular step size. 30
  • 31.  Barnes, David J., and Kölling, Michael. 2012. Objects First with Java, A practical Introduction Using BlueJ (5th Edition). Boston: Preston.  Liang, Y. Daniel. 2011. Introduction to Java Programming, Comprehensive (8th Ed.) Prentice Hall.  http://www.tutorialspoint.com/java/java_decision_making.htm  http://www.homeandlearn.co.uk/java/java.html 31