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

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 

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 Developments
MPEG-4 DevelopmentsMPEG-4 Developments
MPEG-4 Developments
Martin Uren
 
Overview of Selected Current MPEG Activities
Overview of Selected Current MPEG ActivitiesOverview of Selected Current MPEG Activities
Overview of Selected Current MPEG Activities
Alpen-Adria-Universität
 
whitepaper_mpeg-if_understanding_mpeg4
whitepaper_mpeg-if_understanding_mpeg4whitepaper_mpeg-if_understanding_mpeg4
whitepaper_mpeg-if_understanding_mpeg4
aniruddh Tyagi
 
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
 

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
 
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
 
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 Collections
phanleson
 
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
 

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
 
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
 
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptxKripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
 

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

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
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
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
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
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

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