SlideShare ist ein Scribd-Unternehmen logo
1 von 87
Downloaden Sie, um offline zu lesen
Grouping objects
Indefinite iteration - the while loop
2
Konsep Penting
• Collections
• Loops
• Iterators
• Arrays
3
The requirement to group
objects
• Many applications involve collections of
objects:
– Personal organizers.
– Library catalogs.
– Student-record system.
• The number of items to be stored varies.
– Items added.
– Items deleted.
4
A personal notebook
• Notes may be stored.
• Individual notes can be viewed.
• There is no limit to the number of
notes.
• It will tell how many notes are
stored.
• Explore the notebook1 project.
5
Class libraries
• Collections of useful classes.
• Java calls its libraries, packages.
• Grouping objects is a recurring
requirement.
– The java.util package contains
classes for doing this.
6
import java.util.ArrayList;
/**
* ...
*/
public class Notebook
{
// Storage for an arbitrary number of notes.
private ArrayList notes;
/**
* Perform any initialization required for the
* notebook.
*/
public Notebook()
{
notes = new ArrayList();
}
...
}
7
Object structures with
collections
8
Features of the collection
• It increases its capacity as necessary.
• It keeps a private count:
– size() accessor.
• It keeps the objects in order.
• Details of how all this is done are
hidden.
– Does that matter? Does not knowing how
prevent us from using it?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
9
Using the collection
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class MusicOrganizer
{
private ArrayList<String> files;
...
public void addFile(String filename)
{
files.add(filename);
}
public int getNumberOfFiles()
{
return files.size();
}
...
}
Adding a new file
Returning the number of files
(delegation)
10
Index numbering
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
11
Retrieving an object
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Could be invalid !
public void listFile(int index)
{
String filename = files.get(index);
System.out.println(filename);
}
Print the file name Retrieve the file name
12
Retrieving an object
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Index validity checks
public 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?)
13
Removal may affect
numbering
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
14
The general utility of indices
• 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, …
15
Review
• 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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
16
Review
• 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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
17
Interlude:
Some popular errors...
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
18
/**
* Print out info (number of entries).
*/
public void showStatus()
{
if(files.size() == 0); {
System.out.println("Organizer is empty");
}
else {
System.out.print("Organizer holds ");
System.out.println(files.size() + " files");
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
What’s wrong here?
19
/**
* Print out info (number of entries).
*/
public void showStatus()
{
if(files.size() == 0);
{
System.out.println("Organizer is empty");
}
else {
System.out.print("Organizer holds ");
System.out.println(files.size() + "files");
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
This is the same as before!
20
/**
* Print out info (number of entries).
*/
public void showStatus()
{
if(files.size() == 0)
;
{
System.out.println("Organizer is empty");
}
else {
System.out.print("Organizer holds ");
System.out.println(files.size() + "files");
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
This is the same again
21
/**
* Print out info (number of entries).
*/
public void showStatus()
{
if(files.size() == 0) {
;
}
{
System.out.println("Organizer is empty");
}
else {
System.out.print("Organizer holds ");
System.out.println(files.size() + "files");
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
and the same again…
22
/**
* Print out info (number of entries).
*/
public void showStatus()
{
if(isEmpty = true) {
System.out.println("Organizer is empty");
}
else {
System.out.print("Organizer holds ");
System.out.println(files.size() + "files");
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
This time I have a boolean field
called ‘isEmpty’... What’s wrong here?
23
/**
* Print out info (number of entries).
*/
public void showStatus()
{
if(isEmpty == true) {
System.out.println("Organizer is empty");
}
else {
System.out.print("Organizer holds ");
System.out.println(files.size() + "files");
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
This time I have a boolean field
called ‘isEmpty’... The correct version
24
/**
* Store a new file in the organizer. If the
* organizer is full, save it and start a new one.
*/
public void addFile(String filename)
{
if(files.size() == 100)
files.save();
// starting new list
files = new ArrayList<String>();
files.add(filename);
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
What’s wrong here?
25
/**
* Store a new file in the organizer. If the
* organizer is full, save it and start a new one.
*/
public void addFile(String filename)
{
if(files.size == 100)
files.save();
// starting new list
files = new ArrayList<String>();
files.add(filename);
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
This is the same.
26
/**
* Store a new file in the organizer. If the
* organizer is full, save it and start a new one.
*/
public void addFile(String filename)
{
if(files.size == 100) {
files.save();
// starting new list
files = new ArrayList<String>();
}
files.add(filename);
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
The correct version
Grouping objects
Collections and the for-each loop
28
Main concepts to be covered
• Collections
• Loops: the for-each loop
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
29
Iteration
• We often want to perform some actions an
arbitrary number of times.
– E.g., print all the file names in the organizer.
How many are there?
• Most programming languages include loop
statements to make this possible.
• Java has several sorts of loop statement.
– We will start with its for-each loop.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
30
Iteration fundamentals
• We often want to repeat some
actions over and over.
• Loops provide us with a way to
control how many times we repeat
those actions.
• With collections, we often want to
repeat things once for every object
in a particular collection.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
31
For-each loop pseudo code
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
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
32
Iterating over a collection
Iterator it = myCollection.iterator();
while(it.hasNext()) {
call it.next() to get the next object
do something with that object
}
java.util.Iterator
Returns an Iterator
object
public void listNotes()
{
Iterator it = notes.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
33
Review
• Loop statements allow a block of
statements to be repeated.
• The for-each loop allows iteration over a
whole collection.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Grouping objects
Indefinite iteration - the while loop
35
Main concepts to be covered
• The difference between bounded
and unbounded iteration.
• The while loop
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
36
Search tasks are indefinite
• We cannot predict, in advance, how
many places we will have to look.
• Although, there may well be an
absolute limit – i.e., checking every
possible location.
• ‘Infinite loops’ are also possible.
– Through error or the nature of the task.
37
The while loop
• A for-each loop repeats the loop body
for each object in a collection.
• Sometimes we require more variation
than this.
• We use a boolean condition to decide
whether or not to keep going.
• A while loop provides this control.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
38
While loop pseudo code
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
while(loop condition) {
loop body
}
while we wish to continue, do the things in the loop body
boolean test
while keyword
Statements to be repeated
Pseudo-code expression of the actions of
a while loop
General form of a while loop
39
Looking for your keys
while(the keys are missing) {
look in the next place;
}
Or:
while(not (the keys have been found)) {
look in the next place;
}
40
Looking for your keys
boolean searching = true;
while(searching) {
if(they are in the next place) {
searching = false;
}
}
Suppose we don’t find them?
41
A Java example
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**
* List all file names in the organizer.
*/
public void listAllFiles()
{
for(String filename : files) {
System.out.println(filename);
}
}
for each filename in files, print out filename
42
A Java example
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
/**
* List all file names in the organizer.
*/
public void listAllFiles()
{
int index = 0;
while(index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
index++;
}
}
Increment index by 1
while the value of index is less than the size of the collection,
get and print the next file name, and then increment index
43
for-each versus while
• for-each:
– easier to write.
– safer: it is guaranteed to stop.
• while:
– we don’t have to process the whole
collection.
– doesn’t even have to be used with a
collection.
– take care: could be an infinite loop.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
44
Finishing a search
• How do we finish a search?
• Either there are no more items
to check:
index >= files.size()
• Or the item has been found:
found == true
found
! searching
45
Continuing a search
• With a while loop we need to state
the condition for continuing:
• So the loop’s condition will be the
opposite of that for finishing:
index < files.size() && ! found
index < files.size() && searching
• NB: ‘or’ becomes ‘and’ when
inverting everything.
46
Searching a collection
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
int index = 0;
boolean found = false;
while(index < files.size() && !found) {
String file = files.get(index);
if(file.contains(searchString)) {
// We don't need to keep looking.
found = true;
}
else {
index++;
}
}
// Either we found it at index,
// or we searched the whole collection.
47
The String class
• The String class is defined in the
java.lang package.
• It has some special features that
need a little care.
• In particular, comparison of String
objects can be tricky.
48
Side note: String equality
if(input == "bye") {
...
}
if(input.equals("bye")) {
...
}
Always use .equals for text equality.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
tests identity
tests equality
49
Identity vs equality 1
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Other (non-String) objects:
person1 == person2 ?
“Fred”
:Person
person1 person2
“Jill”
:Person
50
Identity vs equality 2
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Other (non-String) objects:
person1 == person2 ?
“Fred”
:Person
person1 person2
“Fred”
:Person
51
Identity vs equality 3
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Other (non-String) objects:
person1 == person2 ?
“Fred”
:Person
person1 person2
“Fred”
:Person
52
Identity vs equality (Strings)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
"bye"
:String
input
"bye"
:String
String input = reader.getInput();
if(input == "bye") {
...
}
== ?
 (may be) false!
== tests identity
53
Identity vs equality (Strings)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
"bye"
:String
input
"bye"
:String
String input = reader.getInput();
if(input.equals("bye")) {
...
}
equals ?
 true!
equals tests
equality
54Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Grouping objects
Iterators
Iterator and iterator()
• Collections have an iterator()
method.
• This returns an Iterator object.
• Iterator<E> has three methods:
– boolean hasNext()
– E next()
– void remove()
57
Using an Iterator object
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Iterator<ElementType> it = myCollection.iterator();
while(it.hasNext()) {
call it.next() to get the next object
do something with that object
}
java.util.Iterator
returns an Iterator object
public void listAllFiles()
{
Iterator<Track> it = files.iterator();
while(it.hasNext()) {
Track tk = it.next();
System.out.println(tk.getDetails());
}
}
58
Iterator mechanics
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
59Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
:Element
myList:List
:Element :Element
:Iterator
myList.iterator()
:Element
60Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
:Element :Element :Element
:Iterator
hasNext()? ✔
next()
Element e = iterator.next();
:Element
:Iterator
myList:List
61Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
:Element :Element :Element
hasNext()? ✔
next()
:Element
:Iterator :Iterator
myList:List
62Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
:Element :Element :Element
hasNext()? ✔
next()
:Element
:Iterator :Iterator
myList:List
63Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
:Element :Element :Element
hasNext()? ✗
:Element
:Iterator
myList:List
64
Index versus Iterator
• Ways to iterate over a collection:
– for-each loop.
• Use if we want to process every element.
– while loop.
• Use if we might want to stop part way through.
• Use for repetition that doesn't involve a collection.
– Iterator object (new).
• Use if we might want to stop part way through (with while).
• Often used with collections where indexed access is not
very efficient, or impossible.
• Use to remove from a collection.
• Iteration is an important programming pattern.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
65
Removing from a collection
Iterator<Track> it = tracks.iterator();
while(it.hasNext()) {
Track t = it.next();
String artist = t.getArtist();
if(artist.equals(artistToRemove)) {
it.remove();
}
}
Use the Iterator’s remove method.
66
Review
• Loop statements allow a block of
statements to be repeated.
• The for-each loop allows iteration over a
whole collection.
• The while loop allows the repetition to be
controlled by a boolean expression.
• All collection classes provide special
Iterator objects that provide sequential
access to a whole collection.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Grouping objects
Arrays
68
What is an Array?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
69
The size of an array is fixed
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
70
Arrays in Java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
71
Declaring Arrays
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
72
Constructing Arrays
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
73
The length variable for 1D Arrays
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
74
The length variable for 2D Arrays
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
75
Example
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
76
Array Initializer
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
77
Enhanced for Statement
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
78Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
79
Enhanced forStatement
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
80
Fixed-size collections
• Sometimes the maximum collection
size can be pre-determined.
• A special fixed-size collection type is
available: an array.
• Unlike the flexible List collections,
arrays can store object references or
primitive-type values.
• Arrays use a special syntax.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
81
Creating an array object
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
public class LogAnalyzer
{
private int[] hourCounts;
private LogfileReader reader;
public LogAnalyzer()
{
hourCounts = new int[24];
reader = new LogfileReader();
}
...
}
Array object creation
— specifies size
Array variable declaration
— does not contain size
82
The hourCounts array
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
83
Using an array
• Square-bracket notation is used to access
an array element: hourCounts[...]
• Elements are used like ordinary variables.
• The target of an assignment:
hourCounts[hour] = ...;
• In an expression:
hourCounts[hour]++;
adjusted = hourCounts[hour] – 3;
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
84
Standard array use
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] hourCounts;
private String[] names;
...
hourCounts = new int[24];
...
hourcounts[i] = 0;
hourcounts[i]++;
System.out.println(hourcounts[i]);
declaration
creation
use
85
Array literals
• Array literals in this form can only be
used in declarations.
• Related uses require new:
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] numbers = { 3, 15, 4, 5 };
declaration,
creation and
initialization
numbers = new int[] {
3, 15, 4, 5
};
• The size is inferred from the data.
86
Array length
• NB: length is a field rather than a
method!
• It cannot be changed – ‘fixed size’.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
private int[] numbers = { 3, 15, 4, 5 };
int n = numbers.length;
no brackets!
87
Review
• 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
(Increment by the same number each
time).
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Weitere ähnliche Inhalte

Was ist angesagt?

Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopSvetlin Nakov
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Lecture 4: Data Types
Lecture 4: Data TypesLecture 4: Data Types
Lecture 4: Data TypesEelco Visser
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Collections generic
Collections genericCollections generic
Collections genericsandhish
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introductionPaulina Szklarska
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 

Was ist angesagt? (20)

Groupingobject
GroupingobjectGroupingobject
Groupingobject
 
Map-Reduce and Apache Hadoop
Map-Reduce and Apache HadoopMap-Reduce and Apache Hadoop
Map-Reduce and Apache Hadoop
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Polymorphism 9
Polymorphism 9Polymorphism 9
Polymorphism 9
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
Lecture 4: Data Types
Lecture 4: Data TypesLecture 4: Data Types
Lecture 4: Data Types
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
04 sorting
04 sorting04 sorting
04 sorting
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Collections generic
Collections genericCollections generic
Collections generic
 
Chapter ii(oop)
Chapter ii(oop)Chapter ii(oop)
Chapter ii(oop)
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Android Architecure Components - introduction
Android Architecure Components - introductionAndroid Architecure Components - introduction
Android Architecure Components - introduction
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Java 103
Java 103Java 103
Java 103
 

Ähnlich wie 4 gouping object

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
 
ECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.comECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.comshanaabe90
 
ECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.comECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.comGVlaxmi7
 
ECET 370 HELPS Education Counseling--ecet370helps.com
ECET 370 HELPS  Education Counseling--ecet370helps.comECET 370 HELPS  Education Counseling--ecet370helps.com
ECET 370 HELPS Education Counseling--ecet370helps.comclaric64
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docxbriancrawford30935
 
ECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.comECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.comagathachristie210
 
ECET 370 Education Planning--ecet370.com
 ECET 370 Education Planning--ecet370.com ECET 370 Education Planning--ecet370.com
ECET 370 Education Planning--ecet370.comWindyMiller46
 
ECET 370 Effective Communication/tutorialrank.com
 ECET 370 Effective Communication/tutorialrank.com ECET 370 Effective Communication/tutorialrank.com
ECET 370 Effective Communication/tutorialrank.comjonhson275
 
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
 
ECET 370 Success Begins/Newtonhelp.com
ECET 370 Success Begins/Newtonhelp.comECET 370 Success Begins/Newtonhelp.com
ECET 370 Success Begins/Newtonhelp.comledlang1
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHPvinaikopp
 
ECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.comECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.comkopiko106
 
ECET 370 Invent Yourself/newtonhelp.com
ECET 370 Invent Yourself/newtonhelp.comECET 370 Invent Yourself/newtonhelp.com
ECET 370 Invent Yourself/newtonhelp.comlechenau124
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookRoman Tsypuk
 

Ähnlich wie 4 gouping object (20)

Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
Chapter08
Chapter08Chapter08
Chapter08
 
ECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.comECET 370 Achievement Education -- www.ecet370.com
ECET 370 Achievement Education -- www.ecet370.com
 
ECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.comECET 370 HELPS Redefined Education--ecet370helps.com
ECET 370 HELPS Redefined Education--ecet370helps.com
 
ECET 370 HELPS Education Counseling--ecet370helps.com
ECET 370 HELPS  Education Counseling--ecet370helps.comECET 370 HELPS  Education Counseling--ecet370helps.com
ECET 370 HELPS Education Counseling--ecet370helps.com
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
 
ECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.comECET 370 Redefined Education--ecet370.com
ECET 370 Redefined Education--ecet370.com
 
ECET 370 Education Planning--ecet370.com
 ECET 370 Education Planning--ecet370.com ECET 370 Education Planning--ecet370.com
ECET 370 Education Planning--ecet370.com
 
ECET 370 Effective Communication/tutorialrank.com
 ECET 370 Effective Communication/tutorialrank.com ECET 370 Effective Communication/tutorialrank.com
ECET 370 Effective Communication/tutorialrank.com
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
ECET 370 Success Begins/Newtonhelp.com
ECET 370 Success Begins/Newtonhelp.comECET 370 Success Begins/Newtonhelp.com
ECET 370 Success Begins/Newtonhelp.com
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
 
ECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.comECET 370 Inspiring Innovation--ecet370.com
ECET 370 Inspiring Innovation--ecet370.com
 
Unit - IV.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.pptx
 
Unit - IV (1).pptx
Unit - IV (1).pptxUnit - IV (1).pptx
Unit - IV (1).pptx
 
ECET 370 Invent Yourself/newtonhelp.com
ECET 370 Invent Yourself/newtonhelp.comECET 370 Invent Yourself/newtonhelp.com
ECET 370 Invent Yourself/newtonhelp.com
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
 

Mehr von Robbie AkaChopa

[Www.akachopa.com]sbmptn 2013 tpa
[Www.akachopa.com]sbmptn 2013 tpa[Www.akachopa.com]sbmptn 2013 tpa
[Www.akachopa.com]sbmptn 2013 tpaRobbie AkaChopa
 
[Www.akachopa.com]sbmptn 2013 tkdu
[Www.akachopa.com]sbmptn 2013 tkdu[Www.akachopa.com]sbmptn 2013 tkdu
[Www.akachopa.com]sbmptn 2013 tkduRobbie AkaChopa
 
[Www.akachopa.com]sbmptn 2013 soshum
[Www.akachopa.com]sbmptn 2013 soshum[Www.akachopa.com]sbmptn 2013 soshum
[Www.akachopa.com]sbmptn 2013 soshumRobbie AkaChopa
 
[Www.akachopa.com]sbmptn 2013 saintek
[Www.akachopa.com]sbmptn 2013 saintek[Www.akachopa.com]sbmptn 2013 saintek
[Www.akachopa.com]sbmptn 2013 saintekRobbie AkaChopa
 
Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...
Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...
Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...Robbie AkaChopa
 
Snmptn 2012 tbs [akachopa.com]
Snmptn 2012 tbs [akachopa.com]Snmptn 2012 tbs [akachopa.com]
Snmptn 2012 tbs [akachopa.com]Robbie AkaChopa
 
Snmptn 2012 ipa [akachopa.com]
Snmptn 2012 ipa [akachopa.com]Snmptn 2012 ipa [akachopa.com]
Snmptn 2012 ipa [akachopa.com]Robbie AkaChopa
 
Snmptn 2012 tpa [akachopa.com]
Snmptn 2012 tpa [akachopa.com]Snmptn 2012 tpa [akachopa.com]
Snmptn 2012 tpa [akachopa.com]Robbie AkaChopa
 
Snmptn 2012 ips [akachopa.com]
Snmptn 2012 ips [akachopa.com]Snmptn 2012 ips [akachopa.com]
Snmptn 2012 ips [akachopa.com]Robbie AkaChopa
 
Inferensi statistik satu populasi
Inferensi statistik satu populasiInferensi statistik satu populasi
Inferensi statistik satu populasiRobbie AkaChopa
 

Mehr von Robbie AkaChopa (20)

Monetisasi blog 1
Monetisasi blog 1Monetisasi blog 1
Monetisasi blog 1
 
[Www.akachopa.com]sbmptn 2013 tpa
[Www.akachopa.com]sbmptn 2013 tpa[Www.akachopa.com]sbmptn 2013 tpa
[Www.akachopa.com]sbmptn 2013 tpa
 
[Www.akachopa.com]sbmptn 2013 tkdu
[Www.akachopa.com]sbmptn 2013 tkdu[Www.akachopa.com]sbmptn 2013 tkdu
[Www.akachopa.com]sbmptn 2013 tkdu
 
[Www.akachopa.com]sbmptn 2013 soshum
[Www.akachopa.com]sbmptn 2013 soshum[Www.akachopa.com]sbmptn 2013 soshum
[Www.akachopa.com]sbmptn 2013 soshum
 
[Www.akachopa.com]sbmptn 2013 saintek
[Www.akachopa.com]sbmptn 2013 saintek[Www.akachopa.com]sbmptn 2013 saintek
[Www.akachopa.com]sbmptn 2013 saintek
 
Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...
Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...
Jadwal pembekalan kkn 73 kelompok iv fak. pertanian, fak. teknik 12 13 juni 2...
 
Hasil seleksisnmptn2014
Hasil seleksisnmptn2014Hasil seleksisnmptn2014
Hasil seleksisnmptn2014
 
Snmptn 2012 tbs [akachopa.com]
Snmptn 2012 tbs [akachopa.com]Snmptn 2012 tbs [akachopa.com]
Snmptn 2012 tbs [akachopa.com]
 
Snmptn 2012 ipa [akachopa.com]
Snmptn 2012 ipa [akachopa.com]Snmptn 2012 ipa [akachopa.com]
Snmptn 2012 ipa [akachopa.com]
 
Snmptn 2012 tpa [akachopa.com]
Snmptn 2012 tpa [akachopa.com]Snmptn 2012 tpa [akachopa.com]
Snmptn 2012 tpa [akachopa.com]
 
Snmptn 2012 ips [akachopa.com]
Snmptn 2012 ips [akachopa.com]Snmptn 2012 ips [akachopa.com]
Snmptn 2012 ips [akachopa.com]
 
Soal stat
Soal statSoal stat
Soal stat
 
10. deadlock
10. deadlock10. deadlock
10. deadlock
 
09 sinkronisasi proses
09 sinkronisasi proses09 sinkronisasi proses
09 sinkronisasi proses
 
Inferensi statistik satu populasi
Inferensi statistik satu populasiInferensi statistik satu populasi
Inferensi statistik satu populasi
 
Inferensi statistik
Inferensi statistikInferensi statistik
Inferensi statistik
 
Tabel distribusi
Tabel distribusiTabel distribusi
Tabel distribusi
 
Indonesian quran-wb
Indonesian quran-wbIndonesian quran-wb
Indonesian quran-wb
 
Al quran-pdf
Al quran-pdfAl quran-pdf
Al quran-pdf
 
Presentation
PresentationPresentation
Presentation
 

Kürzlich hochgeladen

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 

Kürzlich hochgeladen (20)

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 

4 gouping object

  • 2. 2 Konsep Penting • Collections • Loops • Iterators • Arrays
  • 3. 3 The requirement to group objects • Many applications involve collections of objects: – Personal organizers. – Library catalogs. – Student-record system. • The number of items to be stored varies. – Items added. – Items deleted.
  • 4. 4 A personal notebook • Notes may be stored. • Individual notes can be viewed. • There is no limit to the number of notes. • It will tell how many notes are stored. • Explore the notebook1 project.
  • 5. 5 Class libraries • Collections of useful classes. • Java calls its libraries, packages. • Grouping objects is a recurring requirement. – The java.util package contains classes for doing this.
  • 6. 6 import java.util.ArrayList; /** * ... */ public class Notebook { // Storage for an arbitrary number of notes. private ArrayList notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList(); } ... }
  • 8. 8 Features of the collection • It increases its capacity as necessary. • It keeps a private count: – size() accessor. • It keeps the objects in order. • Details of how all this is done are hidden. – Does that matter? Does not knowing how prevent us from using it? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 9. 9 Using the collection Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class MusicOrganizer { private ArrayList<String> files; ... public void addFile(String filename) { files.add(filename); } public int getNumberOfFiles() { return files.size(); } ... } Adding a new file Returning the number of files (delegation)
  • 10. 10 Index numbering Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 11. 11 Retrieving an object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Could be invalid ! public void listFile(int index) { String filename = files.get(index); System.out.println(filename); } Print the file name Retrieve the file name
  • 12. 12 Retrieving an object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Index validity checks public 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?)
  • 13. 13 Removal may affect numbering Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 14. 14 The general utility of indices • 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, …
  • 15. 15 Review • 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 16. 16 Review • 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. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 17. 17 Interlude: Some popular errors... Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 18. 18 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + " files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling What’s wrong here?
  • 19. 19 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This is the same as before!
  • 20. 20 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0) ; { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This is the same again
  • 21. 21 /** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0) { ; } { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling and the same again…
  • 22. 22 /** * Print out info (number of entries). */ public void showStatus() { if(isEmpty = true) { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This time I have a boolean field called ‘isEmpty’... What’s wrong here?
  • 23. 23 /** * Print out info (number of entries). */ public void showStatus() { if(isEmpty == true) { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This time I have a boolean field called ‘isEmpty’... The correct version
  • 24. 24 /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size() == 100) files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling What’s wrong here?
  • 25. 25 /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size == 100) files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling This is the same.
  • 26. 26 /** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size == 100) { files.save(); // starting new list files = new ArrayList<String>(); } files.add(filename); } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The correct version
  • 27. Grouping objects Collections and the for-each loop
  • 28. 28 Main concepts to be covered • Collections • Loops: the for-each loop Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 29. 29 Iteration • We often want to perform some actions an arbitrary number of times. – E.g., print all the file names in the organizer. How many are there? • Most programming languages include loop statements to make this possible. • Java has several sorts of loop statement. – We will start with its for-each loop. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 30. 30 Iteration fundamentals • We often want to repeat some actions over and over. • Loops provide us with a way to control how many times we repeat those actions. • With collections, we often want to repeat things once for every object in a particular collection. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 31. 31 For-each loop pseudo code Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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
  • 32. 32 Iterating over a collection Iterator it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object } java.util.Iterator Returns an Iterator object public void listNotes() { Iterator it = notes.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }
  • 33. 33 Review • Loop statements allow a block of statements to be repeated. • The for-each loop allows iteration over a whole collection. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 35. 35 Main concepts to be covered • The difference between bounded and unbounded iteration. • The while loop Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 36. 36 Search tasks are indefinite • We cannot predict, in advance, how many places we will have to look. • Although, there may well be an absolute limit – i.e., checking every possible location. • ‘Infinite loops’ are also possible. – Through error or the nature of the task.
  • 37. 37 The while loop • A for-each loop repeats the loop body for each object in a collection. • Sometimes we require more variation than this. • We use a boolean condition to decide whether or not to keep going. • A while loop provides this control. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 38. 38 While loop pseudo code Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling while(loop condition) { loop body } while we wish to continue, do the things in the loop body boolean test while keyword Statements to be repeated Pseudo-code expression of the actions of a while loop General form of a while loop
  • 39. 39 Looking for your keys while(the keys are missing) { look in the next place; } Or: while(not (the keys have been found)) { look in the next place; }
  • 40. 40 Looking for your keys boolean searching = true; while(searching) { if(they are in the next place) { searching = false; } } Suppose we don’t find them?
  • 41. 41 A Java example Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * List all file names in the organizer. */ public void listAllFiles() { for(String filename : files) { System.out.println(filename); } } for each filename in files, print out filename
  • 42. 42 A Java example Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * List all file names in the organizer. */ public void listAllFiles() { int index = 0; while(index < files.size()) { String filename = files.get(index); System.out.println(filename); index++; } } Increment index by 1 while the value of index is less than the size of the collection, get and print the next file name, and then increment index
  • 43. 43 for-each versus while • for-each: – easier to write. – safer: it is guaranteed to stop. • while: – we don’t have to process the whole collection. – doesn’t even have to be used with a collection. – take care: could be an infinite loop. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 44. 44 Finishing a search • How do we finish a search? • Either there are no more items to check: index >= files.size() • Or the item has been found: found == true found ! searching
  • 45. 45 Continuing a search • With a while loop we need to state the condition for continuing: • So the loop’s condition will be the opposite of that for finishing: index < files.size() && ! found index < files.size() && searching • NB: ‘or’ becomes ‘and’ when inverting everything.
  • 46. 46 Searching a collection Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int index = 0; boolean found = false; while(index < files.size() && !found) { String file = files.get(index); if(file.contains(searchString)) { // We don't need to keep looking. found = true; } else { index++; } } // Either we found it at index, // or we searched the whole collection.
  • 47. 47 The String class • The String class is defined in the java.lang package. • It has some special features that need a little care. • In particular, comparison of String objects can be tricky.
  • 48. 48 Side note: String equality if(input == "bye") { ... } if(input.equals("bye")) { ... } Always use .equals for text equality. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling tests identity tests equality
  • 49. 49 Identity vs equality 1 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Other (non-String) objects: person1 == person2 ? “Fred” :Person person1 person2 “Jill” :Person
  • 50. 50 Identity vs equality 2 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Other (non-String) objects: person1 == person2 ? “Fred” :Person person1 person2 “Fred” :Person
  • 51. 51 Identity vs equality 3 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Other (non-String) objects: person1 == person2 ? “Fred” :Person person1 person2 “Fred” :Person
  • 52. 52 Identity vs equality (Strings) Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling "bye" :String input "bye" :String String input = reader.getInput(); if(input == "bye") { ... } == ?  (may be) false! == tests identity
  • 53. 53 Identity vs equality (Strings) Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling "bye" :String input "bye" :String String input = reader.getInput(); if(input.equals("bye")) { ... } equals ?  true! equals tests equality
  • 54. 54Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 56. Iterator and iterator() • Collections have an iterator() method. • This returns an Iterator object. • Iterator<E> has three methods: – boolean hasNext() – E next() – void remove()
  • 57. 57 Using an Iterator object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Iterator<ElementType> it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object } java.util.Iterator returns an Iterator object public void listAllFiles() { Iterator<Track> it = files.iterator(); while(it.hasNext()) { Track tk = it.next(); System.out.println(tk.getDetails()); } }
  • 58. 58 Iterator mechanics Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 59. 59Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling :Element myList:List :Element :Element :Iterator myList.iterator() :Element
  • 60. 60Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling :Element :Element :Element :Iterator hasNext()? ✔ next() Element e = iterator.next(); :Element :Iterator myList:List
  • 61. 61Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling :Element :Element :Element hasNext()? ✔ next() :Element :Iterator :Iterator myList:List
  • 62. 62Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling :Element :Element :Element hasNext()? ✔ next() :Element :Iterator :Iterator myList:List
  • 63. 63Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling :Element :Element :Element hasNext()? ✗ :Element :Iterator myList:List
  • 64. 64 Index versus Iterator • Ways to iterate over a collection: – for-each loop. • Use if we want to process every element. – while loop. • Use if we might want to stop part way through. • Use for repetition that doesn't involve a collection. – Iterator object (new). • Use if we might want to stop part way through (with while). • Often used with collections where indexed access is not very efficient, or impossible. • Use to remove from a collection. • Iteration is an important programming pattern. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 65. 65 Removing from a collection Iterator<Track> it = tracks.iterator(); while(it.hasNext()) { Track t = it.next(); String artist = t.getArtist(); if(artist.equals(artistToRemove)) { it.remove(); } } Use the Iterator’s remove method.
  • 66. 66 Review • Loop statements allow a block of statements to be repeated. • The for-each loop allows iteration over a whole collection. • The while loop allows the repetition to be controlled by a boolean expression. • All collection classes provide special Iterator objects that provide sequential access to a whole collection. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 68. 68 What is an Array? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 69. 69 The size of an array is fixed Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 70. 70 Arrays in Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 71. 71 Declaring Arrays Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 72. 72 Constructing Arrays Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 73. 73 The length variable for 1D Arrays Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 74. 74 The length variable for 2D Arrays Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 75. 75 Example Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 76. 76 Array Initializer Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 77. 77 Enhanced for Statement Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 78. 78Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 79. 79 Enhanced forStatement Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 80. 80 Fixed-size collections • Sometimes the maximum collection size can be pre-determined. • A special fixed-size collection type is available: an array. • Unlike the flexible List collections, arrays can store object references or primitive-type values. • Arrays use a special syntax. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 81. 81 Creating an array object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() { hourCounts = new int[24]; reader = new LogfileReader(); } ... } Array object creation — specifies size Array variable declaration — does not contain size
  • 82. 82 The hourCounts array Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 83. 83 Using an array • Square-bracket notation is used to access an array element: hourCounts[...] • Elements are used like ordinary variables. • The target of an assignment: hourCounts[hour] = ...; • In an expression: hourCounts[hour]++; adjusted = hourCounts[hour] – 3; Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
  • 84. 84 Standard array use Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[] hourCounts; private String[] names; ... hourCounts = new int[24]; ... hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]); declaration creation use
  • 85. 85 Array literals • Array literals in this form can only be used in declarations. • Related uses require new: Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[] numbers = { 3, 15, 4, 5 }; declaration, creation and initialization numbers = new int[] { 3, 15, 4, 5 }; • The size is inferred from the data.
  • 86. 86 Array length • NB: length is a field rather than a method! • It cannot be changed – ‘fixed size’. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[] numbers = { 3, 15, 4, 5 }; int n = numbers.length; no brackets!
  • 87. 87 Review • 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 (Increment by the same number each time). Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling