SlideShare a Scribd company logo
1
 To learn how to use debugger to step the behavior of the program
 To learn about object structures with collections – ArrayList.
 To learn about ArrayList features and methods
 To know what does generic classes mean
 Iterations
2
 The debugger is useful for gaining insights into program behavior
whether or not there is a program error.
 The steps should follow in debugger:
◦ Set breakpoints.
◦ Examine variables.
◦ Step through code.
3
4
 A collection of objects can store an arbitrary number of other
objects.
 It is the notion of grouping things so that we can refer to them and
manage them all together.
 A collection might be:
◦ large (all the students in a university)
◦ small (the courses one of the students is taking)
5
Many applications involve collection of objects:
 Personal Organizer:
◦ Electronic calendars store event notes about appointments, meetings, birthdays, and
so on.
◦ New notes are added as future events are arranged, and old notes are deleted as
details of past events are no longer needed.
 Library Catalogs:
◦ Libraries record details about the books and journals they own.
◦ The catalog changes as new books are bought and old ones are put into storage or
discarded.
 Student Record System:
◦ Universities maintain records of students.
◦ Each academic year adds new records to the collection, while the records of those
who have left are moved to an archive collection.
◦ Listing subsets of the collection will be common: all the students taking Computing or
all the students due to graduate this year, for instance
6
 Entries must be accessed efficiently
 The number of items to be stored varies
◦ Need the ability to add and delete items
7
 To understand this concept, we are going to write a class that can help
us organize our music files stored on a computer.
 Our class won’t actually store the file details; instead, it will delegate
that responsibility to the standard ArrayList library class, which will save
us a lot of work.
 Here are the basic operations we will have in the initial version of our
organizer:
◦ It allows tracks to be added to the collection.
◦ It has no predetermined limit on the number of tracks it can store, aside from
the memory limit of the machine on which it is run.
◦ It will tell us how many tracks are in the collection.
◦ It will list all the tracks.
 We shall find that the ArrayList class makes it very easy to provide this
functionality from our own class.
8
 Collections are known as parameterized or generic types.
 Generic classes, in contrast to other classes we have seen so far, do not define
a single type in Java, but potentially many types.
 ArrayList is a parameterized or generic type.
 The ArrayList class, for example, can be used to specify an ArrayList of String,
an ArrayList of Person, an ArrayList of Rectangle, or an ArrayList of any other
class that we have available.
 Each particular ArrayList is a separate type that can be used in declarations of
fields, parameters, and return values.
 The type parameter says what we want a list of:
private ArrayList<Person> members;
private ArrayList<TicketMachine> machines;
9
 Class libraries usually contain tried-and-tested collection classes.
 We don’t have to write everything from scratch. Java calls its libraries,
packages.
◦ The java.util package contains classes for doing this.
10
11
 An ArrayList is a dynamic data structure, meaning items can be
added and removed from the list.
 Each item has an index.
 Index values may change if items are removed (or further items
added).
 We specify:
◦ the type of collection: ArrayList
◦ the type of objects it will contain: <String>
◦ private ArrayList<String> files;
 We say, “ArrayList of String”.
12
 The following figure illustrates how a MusicOrganizer object might
look with two filename strings stored in it; Object Structures with
Collection.
13
14
 There are at least three important features of the ArrayList class that
you should observe:
◦ It is able to increase its internal capacity as required: as more items are
added, it simply makes enough room for them.
◦ It keeps its own private count of how many items it is currently storing.
Its size method returns that count.
size() accessor
 It maintains the order of items you insert into it.
 The add method stores each new item at the end of the list. You can
later retrieve them in the same order.
15
 ArrayList implements list functionality (methods):
◦ add, get, remove, size, etc.
 Once you have a new ArrayList objects, you can add elements to it
with the add method:
◦ listTest.add( "first item" );
◦ listTest.add( "second item" );
◦ listTest.add( "third item" );
◦ listTest.add( 7 );
16
Adding a new file
Returning the number of files
(delegation)
17
public class MusicOrganizer
{
private ArrayList<String> files;
...
public void addFile(String filename)
{
files.add(filename);
}
public int getNumberOfFiles()
{
return files.size();
}
...
}
 Items in the list can be referenced by an Index number, and by using
the get method:
18
Index validity checkspublic void listFile(int index)
{
if(index >= 0 &&
index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
}
else {
// This is not a valid index.
}
} Retrieve and print the file name
Needed? (Error message?)
19
20
 Using integers to index collections has a general utility:
◦ ‘next’ is index + 1
◦ ‘previous’ is index – 1
◦ ‘last’ is list.size() – 1
◦ ‘the first three’ is the items at indices 0, 1, 2
 We could also think about accessing items in sequence: 0, 1, 2, …
21
 Collections allow an arbitrary number of objects
to be stored
 Class libraries usually contain tried-and-tested
collection classes
 Java’s class libraries are called packages
 We have used the ArrayList class from the
java.util package
22
 Items may be added and removed
 Each item has an index
 Index values may change if items are removed
(or further items added)
 The main ArrayList methods are
add, get, remove, and size
 ArrayList is a parameterized or generic type
23
 We often want to repeat some actions over and over
◦ e.g. “do this action for each student in the university”
◦ e.g. “do this action seventeen times”
◦ e.g. “do this action until this condition is true”
 Java loops provide us with a way to control how many times we
repeat these actions
 With collections, we often want to repeat things once for every
object in a particular collection
24
for(ElementType element : collection) {
loop body
}
For each element in collection, do the things in the loop body.
loop header
for keyword
Statement(s) to be repeated
Pseudo-code expression of the
actions of a for-each loop
General form of the for-each loop
25
/**
* List all file names in the organizer.
*/
public void listAllFilesForEachLoop()
{
for(String filename : files) {
System.out.println(filename);
}
}
for each filename in files, print out filename
26
 Statements can be nested, giving greater selectivity:
public void findFiles(String searchString)
{
for(String filename : files) {
if(filename.contains(searchString)) {
System.out.println(filename);
}
}
}
27
public String findFiles(String searchString)
{
for (String filename : files) {
if (filename.contains(searchString)) {
return filename; // return the first match if one is
found
}
}
return “”; //return empty string if NO match is found
}
28
 Easy to write
 Termination happens naturally
 The collection cannot be changed
 There is no index provided
◦ Not all collections are index-based
 We can’t stop part way through
◦ Except when using a return statement
 It provides ‘definite iteration’,
aka ‘bounded iteration’
29
The for-each loop is used whenever we need to perform some action
on every item in a collection:
view every one
change every one
check every one
select some or count some from every one
30
1. Get first element of the collection files
2. Execute statement using that value
3. Get next element from the collection and repeat from 2
4. But if no elements left then stop
for (String filename : files) {
if (filename.contains(searchString)) {
System.out.println(filename);
}
}
31
 We have seen how this results in structures of objects working
together to solve a common task.
 Objects can create other objects, and they can invoke each other’s
methods. Understanding these object interactions is essential in
planning, implementing, and debugging applications.
 We can use pen-and-paper diagrams, code reading, and debuggers
to investigate how an application executes or to track down bugs.
32
 We have made good progress with the basics of organizing our
music collection. We can store the names of any number of music
files and even play them.
 We have done this with relatively little coding effort, because we
have been able to piggyback on the functionality provided by library
classes: ArrayList from the standard Java library and a music player
that uses a third-party class library.
 We have also been able to do this with relatively little knowledge of
the internal workings of these library classes; it was sufficient to
know the names, parameter types, and return types of the key
methods.
33
 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
34

More Related Content

What's hot

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
Surendar Meesala
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Generics
GenericsGenerics
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
java collections
java collectionsjava collections
java collections
javeed_mhd
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
22.collections(1)
22.collections(1)22.collections(1)
22.collections(1)
Sirisha Chillakanti
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Java.util
Java.utilJava.util
Java.util
Ramakrishna kapa
 

What's hot (20)

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java collections
Java collectionsJava collections
Java collections
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Generics
GenericsGenerics
Generics
 
07 java collection
07 java collection07 java collection
07 java collection
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
java collections
java collectionsjava collections
java collections
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
22.collections(1)
22.collections(1)22.collections(1)
22.collections(1)
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Java.util
Java.utilJava.util
Java.util
 
Collections
CollectionsCollections
Collections
 
강의자료6
강의자료6강의자료6
강의자료6
 

Viewers also liked

MPEG-4 BIFS Overview
MPEG-4 BIFS OverviewMPEG-4 BIFS Overview
MPEG-4 BIFS Overview
Cyril Concolato
 
MPEG-4 Developments
MPEG-4 DevelopmentsMPEG-4 Developments
MPEG-4 DevelopmentsMartin Uren
 
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR CONVERGENCE
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR  CONVERGENCEOBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR  CONVERGENCE
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR CONVERGENCE
Jerry Foss
 
MPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio services
MPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio servicesMPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio services
MPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio services
Cyril Concolato
 
Overview of Selected Current MPEG Activities
Overview of Selected Current MPEG ActivitiesOverview of Selected Current MPEG Activities
Overview of Selected Current MPEG ActivitiesAlpen-Adria-Universität
 
whitepaper_mpeg-if_understanding_mpeg4
whitepaper_mpeg-if_understanding_mpeg4whitepaper_mpeg-if_understanding_mpeg4
whitepaper_mpeg-if_understanding_mpeg4aniruddh Tyagi
 
BBC - What is IPTV?
BBC - What is IPTV?BBC - What is IPTV?
BBC - What is IPTV?
internetstreams
 
The Future of IPTV
The Future of IPTVThe Future of IPTV
The Future of IPTV
Raymond Monaco
 
I Minds2009 Future Media Prof Rik Van De Walle (Ibbt Mm Lab U Gent)
I Minds2009 Future Media  Prof  Rik Van De Walle (Ibbt Mm Lab U Gent)I Minds2009 Future Media  Prof  Rik Van De Walle (Ibbt Mm Lab U Gent)
I Minds2009 Future Media Prof Rik Van De Walle (Ibbt Mm Lab U Gent)imec.archive
 
Video Compression Basics
Video Compression BasicsVideo Compression Basics
Video Compression Basics
Sanjiv Malik
 
multimedia element
multimedia elementmultimedia element
multimedia element
AZMAN KADIR
 
State of the Word 2011
State of the Word 2011State of the Word 2011
State of the Word 2011
photomatt
 

Viewers also liked (12)

MPEG-4 BIFS Overview
MPEG-4 BIFS OverviewMPEG-4 BIFS Overview
MPEG-4 BIFS Overview
 
MPEG-4 Developments
MPEG-4 DevelopmentsMPEG-4 Developments
MPEG-4 Developments
 
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR CONVERGENCE
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR  CONVERGENCEOBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR  CONVERGENCE
OBJECT-MEDIA: FROM PERSONALISATION TO A SEAMLESS TV/VR CONVERGENCE
 
MPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio services
MPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio servicesMPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio services
MPEG-4 BIFS and MPEG-2 TS: Latest developments for digital radio services
 
Overview of Selected Current MPEG Activities
Overview of Selected Current MPEG ActivitiesOverview of Selected Current MPEG Activities
Overview of Selected Current MPEG Activities
 
whitepaper_mpeg-if_understanding_mpeg4
whitepaper_mpeg-if_understanding_mpeg4whitepaper_mpeg-if_understanding_mpeg4
whitepaper_mpeg-if_understanding_mpeg4
 
BBC - What is IPTV?
BBC - What is IPTV?BBC - What is IPTV?
BBC - What is IPTV?
 
The Future of IPTV
The Future of IPTVThe Future of IPTV
The Future of IPTV
 
I Minds2009 Future Media Prof Rik Van De Walle (Ibbt Mm Lab U Gent)
I Minds2009 Future Media  Prof  Rik Van De Walle (Ibbt Mm Lab U Gent)I Minds2009 Future Media  Prof  Rik Van De Walle (Ibbt Mm Lab U Gent)
I Minds2009 Future Media Prof Rik Van De Walle (Ibbt Mm Lab U Gent)
 
Video Compression Basics
Video Compression BasicsVideo Compression Basics
Video Compression Basics
 
multimedia element
multimedia elementmultimedia element
multimedia element
 
State of the Word 2011
State of the Word 2011State of the Word 2011
State of the Word 2011
 

Similar to Lecture 4 - Object Interaction and Collections

Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdfRecursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
mallik3000
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
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
Syed Afaq Shah MACS CP
 
4 gouping object
4 gouping object4 gouping object
4 gouping object
Robbie AkaChopa
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Describes the concept of ADTS and illustrates the concept with three o.docx
Describes the concept of ADTS and illustrates the concept with three o.docxDescribes the concept of ADTS and illustrates the concept with three o.docx
Describes the concept of ADTS and illustrates the concept with three o.docx
earleanp
 
set.pptx
set.pptxset.pptx
set.pptx
satyabratPanda2
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
SURBHI SAROHA
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
SivaSankar Gorantla
 
Generics collections
Generics collectionsGenerics collections
Generics collections
Yaswanth Babu Gummadivelli
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
soniya555961
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
IllllBikkySharmaIlll
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
The second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxThe second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docx
oreo10
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
Prof. Dr. K. Adisesha
 
Use Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.pptUse Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.ppt
manishchoudhary91861
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA

Similar to Lecture 4 - Object Interaction and Collections (20)

Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdfRecursively Searching Files and DirectoriesSummaryBuild a class .pdf
Recursively Searching Files and DirectoriesSummaryBuild a class .pdf
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
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
 
4 gouping object
4 gouping object4 gouping object
4 gouping object
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Describes the concept of ADTS and illustrates the concept with three o.docx
Describes the concept of ADTS and illustrates the concept with three o.docxDescribes the concept of ADTS and illustrates the concept with three o.docx
Describes the concept of ADTS and illustrates the concept with three o.docx
 
set.pptx
set.pptxset.pptx
set.pptx
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
My c++
My c++My c++
My c++
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
The second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docxThe second programming assignment (HW4) is designed to help you ga.docx
The second programming assignment (HW4) is designed to help you ga.docx
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Ii pu cs practical viva voce questions
Ii pu cs  practical viva voce questionsIi pu cs  practical viva voce questions
Ii pu cs practical viva voce questions
 
Use Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.pptUse Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.ppt
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 

More from Syed Afaq Shah MACS CP

Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
Syed Afaq Shah MACS CP
 
Lecture 7- Iterator and for loop over arrays
Lecture 7- Iterator and for loop over arraysLecture 7- Iterator and for loop over arrays
Lecture 7- Iterator and for loop over arrays
Syed Afaq Shah MACS CP
 
Lecture 6 - Arrays
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - Arrays
Syed 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 Variables
Syed 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 Constructors
Syed Afaq Shah MACS CP
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
Syed 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 7- Iterator and for loop over arrays
Lecture 7- Iterator and for loop over arraysLecture 7- Iterator and for loop over arrays
Lecture 7- Iterator and for loop over arrays
 
Lecture 6 - Arrays
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - Arrays
 
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

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 

Lecture 4 - Object Interaction and Collections

  • 1. 1
  • 2.  To learn how to use debugger to step the behavior of the program  To learn about object structures with collections – ArrayList.  To learn about ArrayList features and methods  To know what does generic classes mean  Iterations 2
  • 3.  The debugger is useful for gaining insights into program behavior whether or not there is a program error.  The steps should follow in debugger: ◦ Set breakpoints. ◦ Examine variables. ◦ Step through code. 3
  • 4. 4
  • 5.  A collection of objects can store an arbitrary number of other objects.  It is the notion of grouping things so that we can refer to them and manage them all together.  A collection might be: ◦ large (all the students in a university) ◦ small (the courses one of the students is taking) 5
  • 6. Many applications involve collection of objects:  Personal Organizer: ◦ Electronic calendars store event notes about appointments, meetings, birthdays, and so on. ◦ New notes are added as future events are arranged, and old notes are deleted as details of past events are no longer needed.  Library Catalogs: ◦ Libraries record details about the books and journals they own. ◦ The catalog changes as new books are bought and old ones are put into storage or discarded.  Student Record System: ◦ Universities maintain records of students. ◦ Each academic year adds new records to the collection, while the records of those who have left are moved to an archive collection. ◦ Listing subsets of the collection will be common: all the students taking Computing or all the students due to graduate this year, for instance 6
  • 7.  Entries must be accessed efficiently  The number of items to be stored varies ◦ Need the ability to add and delete items 7
  • 8.  To understand this concept, we are going to write a class that can help us organize our music files stored on a computer.  Our class won’t actually store the file details; instead, it will delegate that responsibility to the standard ArrayList library class, which will save us a lot of work.  Here are the basic operations we will have in the initial version of our organizer: ◦ It allows tracks to be added to the collection. ◦ It has no predetermined limit on the number of tracks it can store, aside from the memory limit of the machine on which it is run. ◦ It will tell us how many tracks are in the collection. ◦ It will list all the tracks.  We shall find that the ArrayList class makes it very easy to provide this functionality from our own class. 8
  • 9.  Collections are known as parameterized or generic types.  Generic classes, in contrast to other classes we have seen so far, do not define a single type in Java, but potentially many types.  ArrayList is a parameterized or generic type.  The ArrayList class, for example, can be used to specify an ArrayList of String, an ArrayList of Person, an ArrayList of Rectangle, or an ArrayList of any other class that we have available.  Each particular ArrayList is a separate type that can be used in declarations of fields, parameters, and return values.  The type parameter says what we want a list of: private ArrayList<Person> members; private ArrayList<TicketMachine> machines; 9
  • 10.  Class libraries usually contain tried-and-tested collection classes.  We don’t have to write everything from scratch. Java calls its libraries, packages. ◦ The java.util package contains classes for doing this. 10
  • 11. 11
  • 12.  An ArrayList is a dynamic data structure, meaning items can be added and removed from the list.  Each item has an index.  Index values may change if items are removed (or further items added).  We specify: ◦ the type of collection: ArrayList ◦ the type of objects it will contain: <String> ◦ private ArrayList<String> files;  We say, “ArrayList of String”. 12
  • 13.  The following figure illustrates how a MusicOrganizer object might look with two filename strings stored in it; Object Structures with Collection. 13
  • 14. 14
  • 15.  There are at least three important features of the ArrayList class that you should observe: ◦ It is able to increase its internal capacity as required: as more items are added, it simply makes enough room for them. ◦ It keeps its own private count of how many items it is currently storing. Its size method returns that count. size() accessor  It maintains the order of items you insert into it.  The add method stores each new item at the end of the list. You can later retrieve them in the same order. 15
  • 16.  ArrayList implements list functionality (methods): ◦ add, get, remove, size, etc.  Once you have a new ArrayList objects, you can add elements to it with the add method: ◦ listTest.add( "first item" ); ◦ listTest.add( "second item" ); ◦ listTest.add( "third item" ); ◦ listTest.add( 7 ); 16
  • 17. Adding a new file Returning the number of files (delegation) 17 public class MusicOrganizer { private ArrayList<String> files; ... public void addFile(String filename) { files.add(filename); } public int getNumberOfFiles() { return files.size(); } ... }
  • 18.  Items in the list can be referenced by an Index number, and by using the get method: 18
  • 19. Index validity checkspublic void listFile(int index) { if(index >= 0 && index < files.size()) { String filename = files.get(index); System.out.println(filename); } else { // This is not a valid index. } } Retrieve and print the file name Needed? (Error message?) 19
  • 20. 20
  • 21.  Using integers to index collections has a general utility: ◦ ‘next’ is index + 1 ◦ ‘previous’ is index – 1 ◦ ‘last’ is list.size() – 1 ◦ ‘the first three’ is the items at indices 0, 1, 2  We could also think about accessing items in sequence: 0, 1, 2, … 21
  • 22.  Collections allow an arbitrary number of objects to be stored  Class libraries usually contain tried-and-tested collection classes  Java’s class libraries are called packages  We have used the ArrayList class from the java.util package 22
  • 23.  Items may be added and removed  Each item has an index  Index values may change if items are removed (or further items added)  The main ArrayList methods are add, get, remove, and size  ArrayList is a parameterized or generic type 23
  • 24.  We often want to repeat some actions over and over ◦ e.g. “do this action for each student in the university” ◦ e.g. “do this action seventeen times” ◦ e.g. “do this action until this condition is true”  Java loops provide us with a way to control how many times we repeat these actions  With collections, we often want to repeat things once for every object in a particular collection 24
  • 25. for(ElementType element : collection) { loop body } For each element in collection, do the things in the loop body. loop header for keyword Statement(s) to be repeated Pseudo-code expression of the actions of a for-each loop General form of the for-each loop 25
  • 26. /** * List all file names in the organizer. */ public void listAllFilesForEachLoop() { for(String filename : files) { System.out.println(filename); } } for each filename in files, print out filename 26
  • 27.  Statements can be nested, giving greater selectivity: public void findFiles(String searchString) { for(String filename : files) { if(filename.contains(searchString)) { System.out.println(filename); } } } 27
  • 28. public String findFiles(String searchString) { for (String filename : files) { if (filename.contains(searchString)) { return filename; // return the first match if one is found } } return “”; //return empty string if NO match is found } 28
  • 29.  Easy to write  Termination happens naturally  The collection cannot be changed  There is no index provided ◦ Not all collections are index-based  We can’t stop part way through ◦ Except when using a return statement  It provides ‘definite iteration’, aka ‘bounded iteration’ 29
  • 30. The for-each loop is used whenever we need to perform some action on every item in a collection: view every one change every one check every one select some or count some from every one 30
  • 31. 1. Get first element of the collection files 2. Execute statement using that value 3. Get next element from the collection and repeat from 2 4. But if no elements left then stop for (String filename : files) { if (filename.contains(searchString)) { System.out.println(filename); } } 31
  • 32.  We have seen how this results in structures of objects working together to solve a common task.  Objects can create other objects, and they can invoke each other’s methods. Understanding these object interactions is essential in planning, implementing, and debugging applications.  We can use pen-and-paper diagrams, code reading, and debuggers to investigate how an application executes or to track down bugs. 32
  • 33.  We have made good progress with the basics of organizing our music collection. We can store the names of any number of music files and even play them.  We have done this with relatively little coding effort, because we have been able to piggyback on the functionality provided by library classes: ArrayList from the standard Java library and a music player that uses a third-party class library.  We have also been able to do this with relatively little knowledge of the internal workings of these library classes; it was sufficient to know the names, parameter types, and return types of the key methods. 33
  • 34.  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 34