SlideShare a Scribd company logo
1 of 31
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

What's hot

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryIlio Catallo
 
Array data structure
Array data structureArray data structure
Array data structuremaamir farooq
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to ArraysTareq Hasan
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and InformationSoftNutx
 
L11 array list
L11 array listL11 array list
L11 array listteach4uin
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsFrançois Garillot
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingHariz Mustafa
 

What's hot (20)

Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Array data structure
Array data structureArray data structure
Array data structure
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Java arrays
Java arraysJava arrays
Java arrays
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Python array
Python arrayPython array
Python array
 
Array properties
Array propertiesArray properties
Array properties
 
L11 array list
L11 array listL11 array list
L11 array list
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Collections
CollectionsCollections
Collections
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Array ppt
Array pptArray ppt
Array ppt
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 

Similar to Lecture 7- Iterator and for loop over arrays

oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
3.2 stacks and arrays
3.2   stacks and arrays3.2   stacks and arrays
3.2 stacks and arraysallenbailey
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdfadinathassociates
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)SURBHI SAROHA
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsSyed Afaq Shah MACS CP
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 

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

oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Arrays
ArraysArrays
Arrays
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
3.2 stacks and arrays
3.2   stacks and arrays3.2   stacks and arrays
3.2 stacks and arrays
 
Array
ArrayArray
Array
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
List in java
List in javaList in java
List in java
 
Lists
ListsLists
Lists
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
Array list(1)
Array list(1)Array list(1)
Array list(1)
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 

More from Syed Afaq Shah MACS CP

Lecture 5 - Interaction with for each and while loops
Lecture 5 - Interaction with for each and while loopsLecture 5 - Interaction with for each and while loops
Lecture 5 - Interaction with for each and while loopsSyed Afaq Shah MACS CP
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsSyed Afaq Shah MACS CP
 

More from Syed Afaq Shah MACS CP (6)

Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Lecture 6 - Arrays
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - Arrays
 
Lecture 5 - Interaction with for each and while loops
Lecture 5 - Interaction with for each and while loopsLecture 5 - Interaction with for each and while loops
Lecture 5 - Interaction with for each and while loops
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and ConstructorsLecture 2 - Classes, Fields, Parameters, Methods and Constructors
Lecture 2 - Classes, Fields, Parameters, Methods and Constructors
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Recently uploaded (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

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